package com.wuhao.shootclient;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;

import androidx.core.app.ActivityCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.NetworkUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.takiku.im_lib.call.Call;
import com.takiku.im_lib.defaultImpl.callback.OnMessageReceiveListener;
import com.takiku.im_lib.dispatcher.Connection;
import com.takiku.im_lib.entity.AppMessage;
import com.takiku.im_lib.listener.EventListener;
import com.wuhao.shootclient.adapter.ItemAdapter;
import com.wuhao.shootclient.base.BaseActivity;
import com.wuhao.shootclient.bean.InitFireVo;
import com.wuhao.shootclient.bean.LaserShootDataVo;
import com.wuhao.shootclient.bean.MeteorologicalVo;
import com.wuhao.shootclient.bean.RegistertestVo;
import com.wuhao.shootclient.bean.ResultsBean;
import com.wuhao.shootclient.bean.ShootFireDataTestVo;
import com.wuhao.shootclient.bean.ShootFireDataVo;
import com.wuhao.shootclient.bean.ShootFireVo;
import com.wuhao.shootclient.bean.ShootPaperVo;
import com.wuhao.shootclient.bean.ShootPeopleVo;
import com.wuhao.shootclient.bean.ShootRegisterVo;
import com.wuhao.shootclient.bean.ShootingDataVo;
import com.wuhao.shootclient.module.LivePreviewModule;
import com.wuhao.shootclient.pusher.ws.netty.lis.OnWsMessageReceiveListener;
import com.wuhao.shootclient.pusher.ws.netty.lis.OnWsStatusChangeListener;
import com.wuhao.shootclient.pusher.ws.WsStatus;
import com.wuhao.shootclient.pusher.ws.netty.Client;
import com.wuhao.shootclient.service.CameraService;
import com.wuhao.shootclient.service.UartService;
import com.wuhao.shootclient.service.uart.UartServiceUART;
import com.wuhao.shootclient.ui.activity.Camera2Activity;
import com.wuhao.shootclient.ui.activity.DeviceListActivity;
import com.wuhao.shootclient.ui.widget.AttachButton;
import com.wuhao.shootclient.ui.widget.BlueListDialog;
import com.wuhao.shootclient.ui.widget.FoldableMenu;
import com.wuhao.shootclient.ui.widget.SocketDialog;
import com.wuhao.shootclient.ui.widget.ThresholdDialog;
import com.wuhao.shootclient.util.Ardith;
import com.wuhao.shootclient.util.GlideUtils;
import com.wuhao.shootclient.util.ImageConverter;
import com.wuhao.shootclient.util.ImageUtil;
import com.wuhao.shootclient.util.LogUtil;
import com.wuhao.shootclient.util.LoggerHelper;
import com.wuhao.shootclient.util.MyMediaRecorder;
import com.wuhao.shootclient.util.NetWorkUtils;
import com.wuhao.shootclient.util.NoFastClickUtils;
import com.wuhao.shootclient.util.NotNullHelper;
import com.wuhao.shootclient.util.PTZControl;
import com.wuhao.shootclient.util.SPUtils;
import com.wuhao.shootclient.util.StrUtil;
import com.wuhao.shootclient.util.TimeUtils;
import com.wuhao.shootclient.util.ToastUtils;
import com.wuhao.shootclient.util.UrlHelper;
import com.wuhao.shootclient.util.eventbus.AppEventBus;
import com.wuhao.shootclient.util.eventbus.EventBusCode;
import com.wuhao.shootclient.util.eventbus.EventCenter;
import com.wuhao.shootclient.util.net.WhResponse;
import com.wuhao.shootclient.util.net.callback.DialogCallback;
import com.wuhao.shootclient.util.net.callback.JsonCallback;
import com.wuhao.shootclient.util.tts.SystemTTS;
import com.wuhao.shootclient.vm.DetailViewModel;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;

/**
 * Create by hao on 2019-11-21
 */
public class MainActivity extends BaseActivity implements FoldableMenu.MenuListener, OnWsStatusChangeListener {
    @BindView(R.id.score_target)
    ImageView mScoreTarget;
    @BindView(R.id.ed_device_num)
    EditText mEdDeviceNum;
    @BindView(R.id.ck_bt_set)
    Button mCkBtSet;
    @BindView(R.id.tv_shoot_state)
    TextView mTvShootState;
    @BindView(R.id.rv_list)
    RecyclerView mListScores;
    public static final int msgWhat = 0x1001;
    public static final int refreshTime = 100;
    @BindView(R.id.clear_all)
    AttachButton mClearAll;
    @BindView(R.id.clear_local)
    AttachButton mClearLocal;
    @BindView(R.id.fire)
    AttachButton mFire;
    @BindView(R.id.tv_user_name)
    TextView mTvUserName;
    @BindView(R.id.value_user_name)
    TextView mValueUserName;

    @BindView(R.id.mfab)
    FoldableMenu mFab;
    @BindView(R.id.camera)
    FoldableMenu camera;
    @BindView(R.id.bullets_number)
    FoldableMenu bulletsNumber;
    @BindView(R.id.image_video)
    ImageView imageVideo;
    @BindView(R.id.radiogroup)
    RadioGroup radiogroup;
    @BindView(R.id.rbtn_sim)
    RadioButton rbtnSim;
    @BindView(R.id.rbtn_movie)
    RadioButton rbtnMovie;
    @BindView(R.id.image_target)
    ImageView imageTarget;
    @BindView(R.id.bt_blue_modify)
    Button btBlueModify;
    @BindView(R.id.tv_blue_id)
    TextView tvBlueId;
    @BindView(R.id.bt_threshold)
    Button btSound;
    @BindView(R.id.bt_facerecognition)
    Button btface;
    @BindView(R.id.bt_socket)
    Button btSocket;
    @BindView(R.id.video_target)
    ImageView mVideoTarget;
    @BindView(R.id.bt_control_uuid)
    Button mBtControlUuid;

    //气象信息
    @BindView(R.id.pressure_tx)
    TextView PressureTx;//气压
    @BindView(R.id.temperature_tx)
    TextView TemperatureTx;//温度
    @BindView(R.id.humidity_tx)
    TextView HumidityTx;//湿度
    @BindView(R.id.rainfall_tx)
    TextView RainfallTx;//降雨量
    @BindView(R.id.winddirection_tx)
    TextView WinddirectionTx;//风向
    @BindView(R.id.windspeed_tx)
    TextView WindspeedTx;//风速
    @BindView(R.id.illuminance_tx)
    TextView IlluminanceTx;//光照

    //记弹器
    @BindView(R.id.no_bomb_recorder)
    LinearLayout no_bomb_recorder;//无记弹器布局
    @BindView(R.id.ble_memorizing_layout)
    LinearLayout ble_memorizing_layout;//有记弹器布局
    @BindView(R.id.memorizingBulletsNum)
    TextView memorizingBulletsNum;//记弹数
    @BindView(R.id.memorizingBulletsStr)//记弹数文本
    TextView memorizingBulletsStr;

    private long mTime;
    //是否设置射击位
    private boolean mSetShooting;
    public MyMediaRecorder mRecorder;
    //当前射击位
    private String mShootingNum;
    private int mWidth;
    private int mHeight;

    private int pxWidth;
    private int pxHeight;
    //靶纸id
    private int mPaperId = -1;
    private int mPeopleId = -1;
    private ArrayList<Point> mPoints = new ArrayList<>();
    //子弹表
    private ArrayList<ShootFireVo> mShootDataVos = new ArrayList<>();
    private StandardGSYVideoPlayer videoPlayer;
    private OrientationUtils orientationUtils;
    private int mAllSrore = 0;
    //激光报靶全部环数
    private int mLaserAllSrore = 0;
    //声压锚定值
    private int mDefaultSound = 5000;
    //    震动锚定值
    private int vibrationValue = 600000;
    //12-26混合阈值
    private int vibrationValueBlend = 30;
    //最后一次播报抬枪过高的时间戳 --- 避免蓝牙频繁快速发送角度值导致频繁快速调用语音播报方法导致内存泄露，程序错误
    private static long lastReportTime = 0;
    //抬枪过高播报间隔时间
    private static final long REPORT_INTERVAL = 5000;
    //调试
    private boolean debugBlue = false;
    //开枪间隔
    private int mDefaultFireTime = 400;
    //延迟
    private int mCameraCaptureDelay = 300;
    private int mRaceId; //比赛id
    private int mGroupId; //小组id
    private String mPeopleName = "";

    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    private String imageAddress;
    //ble是否开启
    private Boolean StartEndBoolean = false;
    //保存声音
    private List<Float> soundList = new ArrayList<>();
    //保存蓝牙信息
    private List<Integer> bleList = new ArrayList<>();
    //soc
    private ProgressDialog dialog;
    private Boolean DialogControl = false;

    private boolean bullet_num_today;
    //子弹发数
    private int numberOfHair = 0;
    private ThresholdDialog debugDialog;
    //是否开启记弹器(默认关闭)
    private Boolean isOpenRecordBullet = false;
    //震值列表
    private List<String> socketList = new ArrayList<>();
    //本地震值列表展示
    private List<String> localDisplayList = new ArrayList<>();

    /**
     * 蓝牙相关变量
     */
    private String mBlueAddress;
    private String mBlueName = "";

    private String blueAddressUART;
    private String blueNameUART;
    private UartService mService = null;
    private BluetoothDevice mDevice = null;
    private static final int REQUEST_ENABLE_BT = 2;
    private static final int REQUEST_SELECT_DEVICE = 1;
    private static final int FACE_RECOGNITION_RESULT = 7;
    private static final int FACE_RECOGNITION_REQUEST = 5;
    private static final int UART_PROFILE_DISCONNECTED = 21;
    private static final int UART_PROFILE_CONNECTED = 20;
    private int mState = UART_PROFILE_DISCONNECTED;
    private ArrayList<String> mBluetoothDataVos = new ArrayList<>();

    private BluetoothAdapter mBluetoothAdapter;
    private ItemAdapter mAdapter;
    private SystemTTS mSystemTTS;
    private long mInt;
    //12-26混合阈值
    private long mIntBlend;
    private long mOldInt = 0L;
    private SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");// 日志的输出格式
    private String mBracket;
    private boolean mIsAccordUnbind;
    //    private StringBuffer zdSb = new StringBuffer();

    private String blueId;

    //中心点坐标
    private double proportionHeight = 0;
    private double proportionWidth = 0;

    //模拟靶   是否可用
    private boolean mSimulation = false;
    //实图靶  是否可用
    private boolean mRealGraph = false;
    //是否计弹  （是否报脱靶）
    private boolean mRecordingBullet = false;
    //激光模拟报靶 是否可用
    private boolean mLaserBullet = false;
    private Runnable resetTask = new Runnable() { // 定时任务，在3分钟后重置计数
        @Override
        public void run() {
            isThreeMinutesExceeded = true; // 设置超过3分钟的标志为true
        }
    };

    //补充的记弹器逻辑
    private List<Long> bulletValues = new ArrayList<>(); // 用于存储有效的射击数据
    private boolean isFirstThresholdExceeded = false; // 标记是否为第一次超过阈值
    private boolean isThreeMinutesExceeded = false; // 是否超过3分钟
    private long lastShotTime = 0; // 记录当前射击的时间
    private Integer ActualNumberOfBulletsRecorded = 0;
    ; // 实际记录的子弹数量
    private static final long ONE_MINUTE_MILLIS = 60000; // 1分钟的毫秒数
    private static final long THREE_MINUTES_MILLIS = 180000; // 3分钟的毫秒数
    private Handler handler = new Handler(); // 用于管理定时任务的Handler


    //弹孔长度 记录
    private int mBulletLength = 0;

    //精确报靶和模糊报靶切换
    boolean EnableCircleFloat = false;

    //保存弹孔 便于虚拟吧实图靶切换使用
    private List<ResultsBean> results = new ArrayList<>();

    //第一張靶紙信息
    private ResultsBean.AllPointsBean paper = null;

    private PTZControl ptzControl;

    private LivePreviewModule mLiveModule;
//    private StringBuffer zdSb = new StringBuffer();\

    //气象定时器
    private Timer meteorologicalTimer;

    //蓝牙控制
    private boolean bleConnect = false;

    //递归开枪控制
    private boolean tesxs = false;

    //射击状态   是否正在射击   1进行中  2未开始
    private int shootingState;

    private boolean toBreakOff = false;

    private String blueName;

    private static final String[] CAMERA_PERMISSION = new String[]{//摄像头拍照权限
            Manifest.permission.CAMERA
    };

    //射击模式状态   1鸡蛋器记弹模式   2无鸡蛋器模式不鸡蛋
//    private int patternState;
    @Override
    protected int getContentView() {
        return R.layout.activity_main;
    }

    @Override
    protected View getViewBind() {
        return null;
    }

    /**
     * 外部跳转进入方法
     *
     * @param context
     */
    public static void start(Context context) {
        Intent starter = new Intent(context, MainActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        if (NetworkUtils.isConnected()) {
            //初始化气象定时器
            meteorologicalTimer = new Timer();
            //启动定时任务
            initMeteorologicalMonitor(meteorologicalTimer);
        }
    }

    @Override
    protected void initWidget() {
        mSystemTTS = SystemTTS.getInstance(this);
        //阈值
        vibrationValue = SPUtils.getInstance().getInt("vibrationValue", 600000);
        //12-26混合阈值
        vibrationValueBlend = SPUtils.getInstance().getInt("vibrationValueBlend", 30);
        //是否设置靶机位
        mSetShooting = SPUtils.getInstance().getBoolean("Shooting");

        startWebSocketClient();
        initSpPagerId();
        initSpPeopleId();
        initDialog();
        initEvent();
        //ble名字
        mBlueName = SPUtils.getInstance().getString("blueName");
        mBlueAddress = SPUtils.getInstance().getString("blueAddress");

        blueAddressUART = SPUtils.getInstance().getString("blueAddressUART");
        blueNameUART = SPUtils.getInstance().getString("blueNameUART");

        // 初始化后台服务
        //权限
        checkPermissions();
        //初始化蓝牙 TODO 10.22 换成-> https://github.com/NordicPlayground/Android-nRF-UART
        initBlue();
        initUART();
        //蓝牙自动连接
        // autoBlue();
        initRecycler();
        initSetBt(false);
        mFab.setIconResId(R.mipmap.ic_kaishi, R.mipmap.ic_end, R.mipmap.ic_bazhi, R.mipmap.ic_kaiqiang);
        mFab.setMenuListener(this);
        //移动摄像头
//        camera.setIconResId(R.mipmap.ic_zero, R.mipmap.ic_fifteen, R.mipmap.ic_twenty_five, R.mipmap.ic_kaiqiang);
//        camera.setMenuListener(listener);
//        camera.setVisibility(View.GONE);
        //发
        bulletsNumber.setVisibility(View.GONE);
        bulletsNumber.setIconResId(R.mipmap.ic_five, R.mipmap.ic_ten, R.mipmap.ic_twenty_five);
        bulletsNumber.setMenuListener(falistener);
        ptzControl = new PTZControl();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mSystemTTS.playText("语音播报正常", "default");
            }
        }, 1000);
    }

    @Override
    protected void initData() {
//        NetSDKLib.getInstance().init();
//        mLoginModule = new IPLoginModule();
//        mLiveModule = new LivePreviewModule(MainActivity.this);
//        LoginTask loginTask = new LoginTask();
//        loginTask.execute();.
//        initCeshi();
        //startService(new Intent(this, SocketService.class));
        if (!mEdDeviceNum.isEnabled()) {
            mShootingNum = SPUtils.getInstance().getString("ShootingNum");
            //靶子宽高
//            mScoreTarget.post(new Runnable() {
//                @Override
//                public void run() {
////                    BitmapFactory.Options options = new BitmapFactory.Options();
////                    BitmapFactory.decodeResource(getResources(),R.mipmap.target_chest_circle,options);
////                    //获取图片的宽高
////                    int height = options.outHeight;
////                    int width = options.outWidth;
////
////                    double div = Ardith.div(height, width);
//
//                    mWidth = mScoreTarget.getWidth();
////                    int Height = (int)Math.round(Ardith.mul(mWidth,div));
////
////                    ViewGroup.LayoutParams layoutParams = mScoreTarget.getLayoutParams();
////                    layoutParams.height = Height;
////                    mScoreTarget.setLayoutParams(layoutParams);
////                    ViewGroup.LayoutParams layoutParams1 = imageTarget.getLayoutParams();
////                    layoutParams.height = Height;
////                    imageTarget.setLayoutParams(layoutParams1);
//                    mHeight = mScoreTarget.getHeight();
//                    pxWidth = DensityUtil.dip2px(MainActivity.this, mWidth);
//                    pxHeight = DensityUtil.dip2px(MainActivity.this, mHeight);
//                    LogUtil.error("---宽" + mWidth + "----高" + mHeight);
//                    //进入时先改变坐标
//                    mScoreTarget.setTranslate(mWidth * 0.5, mHeight * 0.5965483555845002);
//                }
//            });
        }

    }

    //------------------------------------------------------TODO 10.22 ------------------------------------------START------------------------------------------------------
    //故意把属性定义在这里
    private UartServiceUART mServiceUART = null;

    private void initUART() {
        Intent bindIntent = new Intent(this, UartServiceUART.class);
        bindService(bindIntent, mServiceConnectionUART, Context.BIND_AUTO_CREATE);
        LocalBroadcastManager.getInstance(this).registerReceiver(statusChangeReceiverUART, makeGattUpdateIntentFilterUART());
    }

    private ServiceConnection mServiceConnectionUART = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
            mServiceUART = ((UartServiceUART.LocalBinder) rawBinder).getService();
            LogUtil.errorBlue("onServiceConnected mService= " + mServiceUART);
            if (!mServiceUART.initialize()) {
                LogUtil.errorBlue("Unable to initialize Bluetooth");
                finish();
            }
        }

        public void onServiceDisconnected(ComponentName classname) {
            ////     mService.disconnect(mDevice);
            mServiceUART = null;
        }
    };

    private final BroadcastReceiver statusChangeReceiverUART = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            final Intent mIntent = intent;
            //**********CONNECTED***********//
            if (action.equals(UartServiceUART.ACTION_GATT_CONNECTED)) {
                runOnUiThread(() -> {
                    LogUtil.errorBlue("BroadcastReceiver:ACTION_GATT_CONNECTED");
                    ToastUtils.show("连接成功");
                    mState = UART_PROFILE_CONNECTED;
                    btBlueModify.setText("断开记弹器");
                    no_bomb_recorder.setVisibility(View.INVISIBLE);//暂无记弹器不可可见
                    ble_memorizing_layout.setVisibility(View.VISIBLE);//数据可见
                    ActualNumberOfBulletsRecorded = 0;//重新记弹
                    memorizingBulletsNum.setText(ActualNumberOfBulletsRecorded.toString());//设置记弹数
                    tvBlueId.setText(mDevice.getName());
                    localDisplayList.add(TimeUtils.getTime() + "--" + mDevice.getName() + "已连接");
                    mSystemTTS.playText("记蛋器连接成功", "default");
                    SPUtils.getInstance().put("blueNameUART", mDevice.getName());
                    SPUtils.getInstance().put("blueAddressUART", mDevice.getAddress());
                    DeviceListActivity.mDeviceListActivity.finish();
                    //关闭蓝牙搜索 结束重连
                    mIsAccordUnbind = false;
                    bleConnect = true;
                    LogUtil.error(mIsAccordUnbind + "conn");
                    mBluetoothAdapter.stopLeScan(mCallbackUART);
                });
            }

            //**********DISCONNECTED***********//
            if (action.equals(UartServiceUART.ACTION_GATT_DISCONNECTED)) {
                runOnUiThread(() -> {
                    LogUtil.errorBlue("BroadcastReceiver:ACTION_GATT_DISCONNECTED");
                    mState = UART_PROFILE_DISCONNECTED;
                    mServiceUART.close();
                    btBlueModify.setText("搜索记弹器");
                    no_bomb_recorder.setVisibility(View.VISIBLE);//暂无记弹器可见
                    ble_memorizing_layout.setVisibility(View.INVISIBLE);//数据不可见
                    localDisplayList.add(TimeUtils.getTime() + "---" + mDevice.getName() + "--断开连接");
                    if (debugDialog != null && debugDialog.isShowing()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                debugDialog.setListRefresh(localDisplayList);
                            }
                        });
                    }
                    if (toBreakOff) {
                        tvBlueId.setText("连接断开");
                        mSystemTTS.playText("记蛋器断开连接,进入非记蛋模式", "default");
                        toBreakOff = false;
                    } else {
                        tvBlueId.setText("连接断开,请重连");
                        mSystemTTS.playText("记蛋器断开连接,请重新连接", "default");
                        LogUtil.error("UART" + mIsAccordUnbind + "dis");
                        //增加重连机制
                        if (!mIsAccordUnbind) {
                            autoBlue();
                        }
                    }

                    bleConnect = false;
                });
            }

            //**********DISCOVERED***********//
            if (action.equals(UartServiceUART.ACTION_GATT_SERVICES_DISCOVERED)) {
                mServiceUART.enableTXNotification();
            }
            //**********AVAILABLE***********//
            if (action.equals(UartServiceUART.ACTION_DATA_AVAILABLE)) {
                try {
                    String Rx_str = new String(intent.getByteArrayExtra(UartServiceUART.EXTRA_DATA), "UTF-8");
                    // 加速度获取
                    Pattern pattern1 = Pattern.compile("(?<=,)\\d+");
                    Matcher matcher1 = pattern1.matcher(Rx_str);
                    if (matcher1.find()) {
                        String firstValue = matcher1.group();
                        mBluetoothDataVos.add(firstValue);
                        localDisplayList.add(TimeUtils.getTime() + " " + firstValue);
                        if (firstValue.length() < 9) {
                            mInt = Integer.parseInt(firstValue);
                        } else {
                            mInt = Integer.parseInt(firstValue.substring(0, 8));
                        }
                        if (!mEdDeviceNum.isEnabled()) {
                            if (isOpenRecordBullet) {
                                if (mInt > vibrationValue) {
                                    recordShot(mInt);
                                }
                            } else {
                                ToastUtils.show(getString(R.string.tos_start_bull_target));
                            }
                        } else {
                            ToastUtils.show(getString(R.string.tos_clear_set_target));
                        }
                        System.out.println("从第一个数据中提取的值：" + firstValue);
                    }

                    // 角度获取
                    Pattern pattern2 = Pattern.compile("\"alarm\":\"(-?\\d+(\\.\\d+)?)");
                    Matcher matcher2 = pattern2.matcher(Rx_str);
                    if (matcher2.find()) {
                        String secondValue = String.valueOf(Math.abs(Double.parseDouble(matcher2.group(1))));
                        mBluetoothDataVos.add(secondValue);
                        localDisplayList.add(TimeUtils.getTime() + " " + secondValue);
                        // 检查当前播报时间
                        long currentTime = System.currentTimeMillis();
                        //大于角度值
                        if (Double.parseDouble(secondValue) > vibrationValueBlend) {
                            //当前时间戳减去最后一次播报时间是否大于间隔时间 - 避免频繁语音播报导致OOM
                            if (currentTime - lastReportTime >= REPORT_INTERVAL) {
                                mSystemTTS.playText("抬枪过高", "default");
                                ToastUtils.show("抬枪过高");
                                //更新最后一次播报时间戳
                                lastReportTime = currentTime;
                            }
                        }
                        System.out.println("从第二个数据中提取的值：" + secondValue);
                    }

                    if (debugDialog.isShowing()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                debugDialog.setListRefresh(localDisplayList);
                            }
                        });
                    }

                } catch (Exception e) {
                    LogUtil.errorBlue(e.toString());
                }
            }
            //************SUPPORT_UART*********//
            if (action.equals(UartServiceUART.DEVICE_DOES_NOT_SUPPORT_UART)) {
                ToastUtils.show("Device doesn't SUPPORT UART. Disconnecting");
                mServiceUART.disconnect();
            }
        }
    };

    // 记录每次射击的数据
    public void recordShot(long mInt) {
        // 获取当前时间
        long currentTime = System.currentTimeMillis();

        // 判断是否为第一次数据
        if (!isFirstThresholdExceeded) {
            // 设置非第一次的标志
            isFirstThresholdExceeded = true;
            // 设置一个定时器为3分钟
            handler.postDelayed(resetTask, THREE_MINUTES_MILLIS);
        } else {
            // 将超过阀值的数值添加到集合
            bulletValues.add(mInt);
            // 判断是否超过1分钟
            if (currentTime - lastShotTime > ONE_MINUTE_MILLIS) {
                // 超过1分钟，开始新的一轮射击，当前为拉枪栓(当前为第一次)
                startoldRound();
            } else {
                // 判断是否超过3分钟
                if (isThreeMinutesExceeded && mInt < calculateAverage() / 2) {
                    startNewRound(); // 进入下一轮
                } else {
                    if (mInt < calculateAverage() / 2) {
                        startNewRound(); // 进入下一轮
                    } else {
                        ActualNumberOfBulletsRecorded++; // 记弹
                        memorizingBulletsNum.setText(String.valueOf(ActualNumberOfBulletsRecorded)); // 更新显示的子弹数量
                        initGradId(mInt);
                    }
                }
            }
        }
        // 更新最后一次射击的时间
        lastShotTime = currentTime;
    }

    // 计算集合中的平均值
    private double calculateAverage() {
        long sum = 0;
        for (long value : bulletValues) {
            sum += value;
        }
        return bulletValues.isEmpty() ? 0 : (double) sum / bulletValues.size(); // 返回平均值
    }

    // 开始新一轮计数
    private void startNewRound() {
        bulletValues.clear(); // 清空集合
        isFirstThresholdExceeded = false; // 重置第一次超过阈值的标志
        isThreeMinutesExceeded = false; // 重置超过3分钟的标志
        lastShotTime = 0; // 重置最后一次射击的时间
        handler.removeCallbacks(resetTask); // 移除定时器任务
    }

    //开始新一轮记弹，但是跳过第一发为拉枪栓的值
    private void startoldRound() {
        bulletValues.clear(); // 清空集合
        isFirstThresholdExceeded = true; // 重置第一次超过阈值的标志
        isThreeMinutesExceeded = false; // 重置超过3分钟的标志
        lastShotTime = 0; // 重置最后一次射击的时间
        handler.removeCallbacks(resetTask); // 移除定时器任务
        // 重新设置一个定时器为3分钟
        handler.postDelayed(resetTask, THREE_MINUTES_MILLIS);
    }

    private void initGradId(long anInt) {
        OkGo.<WhResponse<InitFireVo>>get(UrlHelper.BASE + UrlHelper.SETTING_TARGET_POSITION_FIRE_GRADER_ID)
                .params("number", mShootingNum)

                .execute(new JsonCallback<WhResponse<InitFireVo>>() {
                    @Override
                    public void onSuccess(Response<WhResponse<InitFireVo>> response) {
                        InitFireVo data = response.body().data;
                        if (data != null) {
                            SPUtils.getInstance().put("RaceId", data.getRace_id());
                            SPUtils.getInstance().put("GroupId", data.getGroup_id());
                            SPUtils.getInstance().put("PeopleId", data.getPeople_id());
                            LogUtil.error("rid" + data.getRace_id() + "--gid" + data.getGroup_id() + "----pe" + data.getPeople_id());
                            initFireTest(anInt);
                        }
                    }

                    @Override
                    public void onError(Response<WhResponse<InitFireVo>> response) {
                        super.onError(response);

                        LogUtil.error("-----" + "请求失败" + response.getException().toString());
                    }
                });


    }

    private static IntentFilter makeGattUpdateIntentFilterUART() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UartServiceUART.ACTION_GATT_CONNECTED);
        intentFilter.addAction(UartServiceUART.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(UartServiceUART.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(UartServiceUART.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(UartServiceUART.DEVICE_DOES_NOT_SUPPORT_UART);
        return intentFilter;
    }

    //蓝牙扫描回调
    private BluetoothAdapter.LeScanCallback mCallbackUART = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (device.getName() != null && !device.getName().isEmpty()) {
                LogUtil.error("----result----" + device.getName() + "--Address----" + device.getAddress());
            }
            if (device.getAddress().equals(SPUtils.getInstance().getString("blueAddressUART")) && blueName.startsWith(SPUtils.getInstance().getString("blueNameUART"))) {
                mServiceUART.connect(SPUtils.getInstance().getString("blueAddressUART"));

            } else if (SPUtils.getInstance().getString("blueAddressUART").isEmpty() && SPUtils.getInstance().getString("blueNameUART").isEmpty()) {
                //  mSystemTTS.playText("虫连失败", "11");
            } else if (device.getName() != null && SPUtils.getInstance().getString("blueNameUART").startsWith("PW02")) {
                LogUtil.error("---------" + device.getName());
                mBluetoothAdapter.stopLeScan(mCallbackUART);
                mBluetoothAdapter.startLeScan(mCallbackUART);
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_SELECT_DEVICE:
                // 如果选择搜索到的蓝牙设备页面操作成功（即选择远程设备成功，并返回所选择的远程设备地址信息）
                if (resultCode == Activity.RESULT_OK && data != null) {
                    String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
                    String devicesName = data.getStringExtra("123");
                    LogUtil.error("----" + devicesName);
                    mDevice = mBluetoothAdapter.getRemoteDevice(deviceAddress);
                    boolean isconnected;
                    if (devicesName.startsWith("AE")) {
                        isconnected = mServiceUART.connect(deviceAddress);
                    } else {
                        isconnected = mService.connect(deviceAddress);
                    }
                    blueName = devicesName;
                    LogUtil.errorBlue("远程蓝牙Address：" + deviceAddress);
                    LogUtil.errorBlue("远程蓝牙Address：" + mDevice);
                    LogUtil.errorBlue("mserviceValue:" + mServiceUART.toString());
                    LogUtil.errorBlue("已连接吗？" + isconnected);
                    //建立成功禁止点击
                }
                break;
            case REQUEST_ENABLE_BT:
                // 如果请求打开蓝牙页面操作成功（蓝牙成功打开）
                if (resultCode == Activity.RESULT_OK) {
                    ToastUtils.show("蓝牙已经成功打开");
                } else {
                    // 请求打开蓝牙页面操作不成功（蓝牙为打开或者打开错误）
                    // Log.d(TAG, "蓝牙未打开");
                    LogUtil.errorBlue("蓝牙未打开");
                    ToastUtils.show("打开蓝牙时发生错误");
                    finish();
                }
                break;
            case FACE_RECOGNITION_REQUEST:
                if (data != null) {
                    if (data.getIntExtra("code", 400) == 200 && !data.getStringExtra("name").isEmpty()) {
                        String name = data.getStringExtra("name");
                        String result = (name.length() > 2) ? name.substring(0, 2) + ".." : name;
                        btface.setText("已识别-" + result);
                        btface.setTextColor(Color.parseColor("#008B45"));
                    }
                }
            default:
                LogUtil.errorBlue("wrong request code");
                break;
        }
    }
    //------------------------------------------------------TODO 10.22 ------------------------------------------END------------------------------------------------------

    private void autoBlue() {
//        new Handler().postDelayed(() -> {
//            if (mBluetoothAdapter != null) {
//                Log.e("debug+++++++",mBluetoothAdapter.isEnabled()+"");
        new Thread(() -> {
//            try {
//                Thread.sleep(5000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            if (blueName.startsWith("AE")) {
                mBluetoothAdapter.startLeScan(mCallbackUART);
            } else {
                mBluetoothAdapter.startLeScan(mCallback);
            }


        }).start();

//            }
//        }, 3000);
    }

    //蓝牙扫描回调
    private BluetoothAdapter.LeScanCallback mCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (device.getName() != null && !device.getName().isEmpty()) {
                LogUtil.error("----result----" + device.getName() + "--Address----" + device.getAddress());
            }
//            LogUtil.error("-----------device.getName() "+device.getName()+"--mBlueName--"+mBlueName+"  "+"mBlueAddress: "+mBlueAddress+" "+"device.getAddress(): "+device.getAddress());
            if (device.getAddress().equals(SPUtils.getInstance().getString("blueAddress")) && device.getName().equals(SPUtils.getInstance().getString("blueName"))) {
                mService.connect(SPUtils.getInstance().getString("blueAddress"));

            } else if (SPUtils.getInstance().getString("blueAddress").isEmpty() && SPUtils.getInstance().getString("blueName").isEmpty()) {
                //  mSystemTTS.playText("虫连失败", "11");
            } else if (device.getName() != null && device.getName().equals("PW02")) {
                mBluetoothAdapter.stopLeScan(mCallback);
                mBluetoothAdapter.startLeScan(mCallback);
            }
        }
    };


    //连接内存保存的蓝牙
    private void initBlue() {
        LogUtil.errorBlue("初始化蓝牙服务");
        Intent bindIntent = new Intent(this, UartService.class);
        bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
        registerReceiver(UARTStatusChangeReceiver,
                makeGattUpdateIntentFilter());
    }

    // UART service connected/disconnected
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        // 与UART服务的连接建立
        @Override
        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
            mService = ((UartService.LocalBinder) rawBinder).getService();
            LogUtil.errorBlue("uart服务对象：" + mService);
            if (!mService.initialize()) {
                LogUtil.errorBlue("创建蓝牙适配器失败");
                // 因为创建蓝牙适配器失败，导致下面的工作无法进展，所以需要关闭当前uart服务
                finish();
            }
        }

        // 与UART服务的连接失去
        @Override
        public void onServiceDisconnected(ComponentName classname) {
            // mService.disconnect(mDevice);
            mService = null;
        }
    };

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UartService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(UartService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(UartService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(UartService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(UartService.DEVICE_DOES_NOT_SUPPORT_UART);
        return intentFilter;
    }


    private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            final Intent mIntent = intent;
            // 建立连接
            if (action.equals(UartService.ACTION_GATT_CONNECTED)) {
                LogUtil.errorBlue("BroadcastReceiver:ACTION_GATT_CONNECTED");
                ToastUtils.show("连接成功");
                // textview_iscConnected.setText("已建立连接");
                String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
//                mBluetoothDataVos.add(new BluetoothDataVo(mDevice.getName(), mDevice.getAddress(), " Connected to: " + mDevice.getName(), "[" + myLogSdf.format(new Date()) + "]"));
                //  messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
                mState = UART_PROFILE_CONNECTED;
                btBlueModify.setText("断开记弹器");

                tvBlueId.setText(mDevice.getName());
                localDisplayList.add(TimeUtils.getTime() + "--" + mDevice.getName() + "已连接");
                if (debugDialog != null && debugDialog.isShowing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            debugDialog.setListRefresh(localDisplayList);
                        }
                    });
                }
                SPUtils.getInstance().put("blueName", mDevice.getName());
                SPUtils.getInstance().put("blueAddress", mDevice.getAddress());
                DeviceListActivity.mDeviceListActivity.finish();
                //关闭蓝牙搜索 结束重连
                mIsAccordUnbind = false;
                LogUtil.error("UART" + mIsAccordUnbind + "conn");
                mBluetoothAdapter.stopLeScan(mCallback);
                bleConnect = true;
            }
            // 断开连接
            if (action.equals(UartService.ACTION_GATT_DISCONNECTED)) {
                LogUtil.errorBlue("BroadcastReceiver:ACTION_GATT_DISCONNECTED");
                mState = UART_PROFILE_DISCONNECTED;
                mService.close();
                btBlueModify.setText("搜索记弹器");

                localDisplayList.add(TimeUtils.getTime() + "--" + mDevice.getName() + "--断开连接");
                if (debugDialog != null && debugDialog.isShowing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            debugDialog.setListRefresh(localDisplayList);
                        }
                    });
                }
                if (toBreakOff) {
                    tvBlueId.setText("连接断开");
                    mSystemTTS.playText("记蛋器断开连接,进入非记蛋模式", "default");
                    toBreakOff = false;
                } else {
                    tvBlueId.setText("连接断开,请重连");
                    mSystemTTS.playText("记蛋器断开连接,请重新连接", "default");
                    LogUtil.error("UART" + mIsAccordUnbind + "dis");
                    //增加重连机制
                    if (!mIsAccordUnbind) {
                        autoBlue();
                    }
                }


                bleConnect = false;

            }
            // 有数据可以接收
            if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {
                byte[] rxValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);
                try {
                    String Rx_str = new String(rxValue, "UTF-8");

                    Date nowtime = new Date();
                    // "[" + myLogSdf.format(new Date())+ "] Connected to: " +
//                    mBluetoothDataVos.add(new BluetoothDataVo(mDevice.getName(), mDevice.getAddress(), Rx_str, "[" + myLogSdf.format(new Date()) + "]"));
                    mBluetoothDataVos.add(Rx_str);
                    localDisplayList.add(TimeUtils.getTime() + "--" + Rx_str);
                    if (debugDialog != null && debugDialog.isShowing()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                debugDialog.setListRefresh(localDisplayList);
                            }
                        });
                    }
//                    blueListDialog.setList(mBluetoothDataVos);
                    //阈值
                    // String s = Rx_str.replaceAll("[( )]", "");
                    Rx_str = Rx_str.replaceAll("^\\)\\(", "(");
                    Rx_str = Rx_str.replaceAll("\\)\\(", ")");
                    if (!Rx_str.substring(0, 1).equals("(")) {
                        //开头是(
                        LogUtil.error("---开头加了(");
                        Rx_str = "(" + Rx_str;
                    } else if (!Rx_str.endsWith(")")) {
                        LogUtil.error("---结尾加了)");
                        Rx_str = Rx_str + ")";
                    } else {
                        LogUtil.error("---开头有(结尾有)");
                    }
                    String bracket = Rx_str.substring(Rx_str.indexOf("(") + 1, Rx_str.indexOf(")"));
                    if (bracket.length() < 9) {
                        mInt = Integer.parseInt(bracket);
                    } else {
                        mInt = Integer.parseInt(bracket.substring(0, 8));
                    }
                  /*  //上一发 赋值
                    if ((mOldInt - mInt) >= (mInt * 0.2)) {
                        //正常阈值
                        LogUtil.error((mOldInt - mInt) + "-----" + (mInt * 0.2) + "--大于-" + mInt);
                        mOldInt = mInt;
                        if (vibrationValue < 1500000) {
                            //步枪
                            vibrationValue = 120000;

                        } else {
                            //手枪
                            vibrationValue = 1900000;
                        }
                    } else {
                        //最后一发阈值
                        LogUtil.error((mOldInt - mInt) + "-----" + (mInt * 0.2) + "--小于-" + mInt);
                        mOldInt = mInt;
                        if (vibrationValue < 1500000) {
                            //步枪
                            vibrationValue = 250000;
                        } else {
                            //手枪
                            vibrationValue = 2200000;
                        }

                    }*/
                    if (mInt > vibrationValue) {
//                        if (!DoubleUtils.isFastDoubleClick()) {
//                            initFire();
                        if (!mEdDeviceNum.isEnabled()) {
                            // TODO: 2020/11/1
                            initGradId(mInt);
                        } else {
                            ToastUtils.show(getString(R.string.tos_clear_set_target));
                        }
//
//                        }
                    }
                } catch (Exception e) {
                    LogUtil.errorBlue(e.toString());
                }
                //预留
              /*  String Rx_str = "";
                for (int i = 0; i < rxValue.length; i++) {
                    if (rxValue[i] >= 0)
                        Rx_str = Rx_str + Integer.toHexString(rxValue[i]) + " ";
                    else
                        Rx_str = Rx_str + Integer.toHexString(rxValue[i] & 0x0ff) + " ";
                }
                listAdapter.add("[" + DateFormat.getTimeInstance().format(new Date()) + "] RX: " + Rx_str);
                messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
            textViewRecLength.setText(Integer.toString(rxValue.length));
            textViewRecNumVal.setText((++recValueNum) + "");*/
            }

            // 未知功能1
            if (action.equals(UartService.ACTION_GATT_SERVICES_DISCOVERED)) {
                mService.enableTXNotification();
            }
            // 未知功能2
            if (action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_UART)) {
                ToastUtils.show("Device doesn't support UART. Disconnecting");
                mService.disconnect();
            }
        }
    };

    /**
     * 蓝牙转菊花
     */
    private void initDialog() {
        dialog = new ProgressDialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMessage("连接硬件设备中...");

        blueListDialog = new BlueListDialog(this);
        blueListDialog.setTitle("点击连接设备");
        blueListDialog.setShutDown("取消");
        blueListDialog.setItemOnClickListener(new BlueListDialog.OnClickItemListener() {
            @Override
            public void onItemDownClick(int position) {
                blueListDialog.showItem();
            }
        });

        blueListDialog.setOnClickShotListener(new BlueListDialog.OnClickShotListener() {
            @Override
            public void onShotDownClick() {
                //停止扫描并关闭弹窗
                blueListDialog.dismiss();
            }
        });
    }


    private FoldableMenu.MenuListener falistener = new FoldableMenu.MenuListener() {
        @Override
        public void onClick(int index) {
            switch (index) {
                case 1:
                    numberOfHair = 5;
                    ToastUtils.show(numberOfHair + "发");
                    break;
                case 2:
                    numberOfHair = 10;
                    ToastUtils.show(numberOfHair + "发");
                    break;
                case 3:
                    numberOfHair = 15;
                    ToastUtils.show(numberOfHair + "发");
                    break;
            }
        }

        @Override
        public void onOpen(boolean isClose) {

        }
    };

    private int initSpPeopleId() {
        mPeopleId = SPUtils.getInstance().getInt("PeopleId", -1);

        return mPeopleId;
    }

    private int initSpPagerId() {
        mPaperId = SPUtils.getInstance().getInt("PagerId", -1);

        return mPaperId;
    }

    private int initSpRace_Id() {
        mRaceId = SPUtils.getInstance().getInt("RaceId", -1);

        return mRaceId;
    }

    private int initSpGroup_Id() {
        mGroupId = SPUtils.getInstance().getInt("GroupId", -1);

        return mGroupId;
    }

    /**
     * 设置靶子按钮状态
     *
     * @param setShooting 设置靶位成功
     */
    private void initSetBt(boolean setShooting) {
        mShootingNum = SPUtils.getInstance().getString("ShootingNum");
        if (setShooting) {
            //  mShootingNum = SPUtils.getInstance().getString("ShootingNum");
            mEdDeviceNum.setText(mShootingNum);
            mEdDeviceNum.setEnabled(false);
            mCkBtSet.setText(getString(R.string.title_modify_target));
        } else {
            mEdDeviceNum.setText(mShootingNum);
            mEdDeviceNum.setEnabled(true);
            mCkBtSet.setText(getString(R.string.bt_target_position));
            mLaserBullet = false;
        }
    }

    /**
     * 初始化list
     */
    private void initRecycler() {
        LinearLayoutManager customLinearLayoutManager = new LinearLayoutManager(this);
        mListScores.setHasFixedSize(true);
        mListScores.setLayoutManager(customLinearLayoutManager);
        mListScores.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mAdapter = new ItemAdapter(null);
        // mAdapter.setOnItemClickListener(this);
        View headView = getLayoutInflater().inflate(R.layout.item_list, (ViewGroup) mListScores.getParent(), false);
        mAdapter.addHeaderView(headView);
        mListScores.setAdapter(mAdapter);
    }

    @Override
    protected void onResume() {
        // while onResume we should logout the device.
//        mLoginModule.logout();
        super.onResume();
    }

    @OnClick({R.id.firebtn, R.id.ck_bt_set, R.id.clear_all, R.id.clear_local, R.id.fire, R.id.image_video, R.id.rbtn_sim, R.id.bt_blue_modify, R.id.bt_threshold, R.id.bt_socket, R.id.bt_control_uuid, R.id.bt_facerecognition})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ck_bt_set:
                //注册靶位
                //第一次设置
                switchUnknwn();
                break;
            case R.id.clear_all:
                //换靶纸
                if (mEdDeviceNum.isEnabled()) {
                    mSystemTTS.playText(getString(R.string.tts_clear_set_target), "default");
                } else {

                    initChangePaPer();
                }
                break;
            case R.id.fire:
                //开枪辅助
                if (NoFastClickUtils.isFastClick(mDefaultFireTime)) {
                    LogUtil.info("第二次");
                    return;
                }
                LogUtil.info("第一次");
                if (mEdDeviceNum.isEnabled()) {
                    mSystemTTS.playText(getString(R.string.tts_clear_set_target), "default");
                } else {
                    ToastUtils.show(R.string.tos_Identifying_bullet_holes);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            initFireTest(0);
//                            initFire();
                        }
                    }, 1500);
                }
                break;
            case R.id.rbtn_sim:
                if (mRealGraph || rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
                    initImage();
                } else {
                    ToastUtils.show("暂无权限可用");
                }
                break;
            //修改蓝牙设备
            case R.id.bt_blue_modify:
                //扫描全部蓝牙
                if (mCallback != null) {
//                    mBluetoothAdapter.stopLeScan(mCallback);
                }
                if (!mBluetoothAdapter.isEnabled()) {
                    ToastUtils.show(getString(R.string.main_ble_open));
                    // 弹出请求打开蓝牙对话框
                    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
                } else {
                    // 如果已经打开蓝牙则与远程蓝牙设备进行连接
                    if (btBlueModify.getText().equals("搜索记弹器")) {
                        /**
                         * 当"scan"按钮点击后，进入DeviceListActivity.class类，弹出该类对应的窗口
                         * ，并自动在窗口内搜索周围的蓝牙设备
                         */
                        if (mRecordingBullet) {
                            Intent newIntent =
                                    new Intent(this, DeviceListActivity.class);
                            startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
                        }
//                        else if(patternState == 1){
//                            Intent newIntent = new Intent(this, DeviceListActivity.class);
//                            startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
//                        }
                        else if (shootingState == 1) {
                            ToastUtils.show("请先结束射击");
                        } else if (!mRecordingBullet) {
                            ToastUtils.show("请开启记弹");
                        }

                    } else {
                        /**
                         * 当scan按钮点击之后，该按钮就会变成stop按钮， 如果此时点击了stop按钮，那么就会执行下面的内容
                         */
                        if (System.currentTimeMillis() - mTime < 1500) {
                            if (mDevice != null) {
                                // 断开连接
                                if (shootingState == 2) {
                                    mIsAccordUnbind = true;
//                                    mService.disconnect();
                                    //TODO 10.22换成UART
                                    if (blueName.startsWith("AE")) {
                                        mServiceUART.disconnect();
                                    } else {
                                        mService.disconnect();
                                    }

                                } else {
                                    ToastUtils.show("请先结束射击");
                                }
                            }
                        } else {
                            ToastUtils.show(R.string.tos_double_click_unbind);
                            mTime = System.currentTimeMillis();
                        }

                    }
                }

                break;
            //射击阈值校准
            case R.id.firebtn:
                mShootingNum = "2";
                initFireTest(0);
                break;
            case R.id.bt_threshold:
                debuggingDialog();
//                if (task == null){
//                    task = new TimerTask() {
//                        @Override
//                        public void run() {
////                            ap++;
//                            initFireTest(0);
////                            if (ap>20){
////                                ap = 0;
////                                if (timer!=null){
////                                    timer.cancel();
////                                    timer = null;
////                                }
////                                if (task!=null){
////                                    task.cancel();
////                                    task = null;
////                                }
////                            }
//                        }
//                    };
//                }
//                if (timer == null){
//                    timer = new Timer();
//                }
//                timer.schedule(task,0,500);
                break;
            //socket 心跳测试专用
            case R.id.bt_socket:
//                aa = 0;
//                if (timer!=null){
//                    ap = 0;
//                    timer.cancel();
//                    timer = null;
//                }
//                if (task!=null){
//                    ap = 0;
//                    task.cancel();
//                    task = null;
//                }
//                Log.e("-=-=-=-=-=-=-=task","task结束||||||||||||||||||||||||||||||||||||||||||||||||||");
                socketDialog = new SocketDialog(this);
                socketDialog.setTitle("心跳");
                socketDialog.setList(socketList);
                socketDialog.show();
                break;
            case R.id.bt_control_uuid:
                //切换鸡蛋器
                UUIDDialog();
                break;
            case R.id.bt_facerecognition://人脸识别
                if (checkPermissions(CAMERA_PERMISSION)) {
                    Intent intent = new Intent(this, Camera2Activity.class);
                    startActivityForResult(intent, 5);
                } else {
                    ActivityCompat.requestPermissions(this, CAMERA_PERMISSION, 2);
                }

                break;
            default:
                break;
        }
    }

    private void UUIDDialog() {
        new AlertDialog.Builder(this)
                .setItems(new String[]{"PW", "六轴"}, uuidclick)
                .show();
    }

    private DialogInterface.OnClickListener uuidclick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (!btBlueModify.getText().equals("搜索记弹器")) {
                if (mDevice != null) {
                    // 断开连接
                    mIsAccordUnbind = true;
                    mService.disconnect();
                    btBlueModify.setText("搜索记弹器");
                    tvBlueId.setText("暂无");
                }
            }

            //关闭蓝牙
            try {
                // 解注册广播过滤器
                unregisterReceiver(UARTStatusChangeReceiver);
            } catch (Exception ignore) {
                LogUtil.error(ignore.toString());
            }
            // 解绑定服务
            unbindService(mServiceConnection);
            // 关闭服务对象
            mService.stopSelf();
            mService = null;

            UartService.CONTROL_UUID = which;

            TimerTask task = new TimerTask() {
                public void run() {
                    //method
//                    initBlue();
                    initUART();
                    initBlue();
                }
            };
            Timer timer = new Timer();
            timer.schedule(task, 1000);
        }
    };

    private void debuggingDialog() {
//        if (localDisplayList.size() != 0) {
        if (true) {
            debugDialog = new ThresholdDialog(this);
            debugDialog.setTitle("开始调试");
            debugDialog.setList(localDisplayList);
            debugDialog.setThreshold(vibrationValue);
            debugDialog.setThresholdblend(vibrationValueBlend);
            debugDialog.setButOnClickListener(new ThresholdDialog.OnClickButListener() {
                @Override
                public void onButDownClick(String threshold, String thresholdBlend) {
                    if ((threshold != null && !threshold.equals(""))) {
                        vibrationValue = Integer.valueOf(threshold);
                        SPUtils.getInstance().put("vibrationValue", Integer.valueOf(threshold));
                    }
                    if ((thresholdBlend != null && !thresholdBlend.equals(""))) {
                        vibrationValueBlend = Integer.valueOf(thresholdBlend);
                        SPUtils.getInstance().put("vibrationValueBlend", Integer.valueOf(thresholdBlend));
                    }
                    debugDialog.dismiss();
                }
            });
            debugDialog.show();
        } else {
            ToastUtils.show("暂无数据");
        }
    }

    //eventbus 消息传递 socket
    @Override
    protected void onEventComing(EventCenter center) {
        int eventCode = center.getEventCode();
        Gson gson = new Gson();
        switch (eventCode) {
            //socket消息
            case EventBusCode.EVENT_TYPE:
                String str = (String) center.getData();
                int errorCode = 0;
                try {
                    JSONObject object = new JSONObject(str);
                    errorCode = object.getInt("code");
                    LoggerHelper.e("onEventComing", "errorCode:" + errorCode);
                    switch (errorCode) {
                        case 26:
                            long runtime = System.currentTimeMillis();
                            if (mLaserBullet) {
                                //获取激光点数据
                                LaserShootDataVo laserShootDataVo = gson.fromJson(str, LaserShootDataVo.class);
                                //激光点数据
                                ShootingDataVo.DataBean laserShootDataVoData = laserShootDataVo.getData();
                                //激光总环数
                                mLaserAllSrore = mLaserAllSrore + StrUtil.Format(laserShootDataVoData.getPointI().getScore());
                                //填充Recycler的数据
                                mShootDataVos.add(new ShootFireVo(laserShootDataVoData.getPointI().getScore(),
                                        laserShootDataVoData.getPointI().getOrientation(),
                                        laserShootDataVoData.getPointI().getAngel(),
                                        laserShootDataVoData.getPointI().getX(),
                                        laserShootDataVoData.getPointI().getY(),
                                        mLaserAllSrore));
                                //模拟靶
                                if (rbtnSim.getText().toString().equals(getString(R.string.rb_simulation_target))) {
                                    changeImgStatus();
//                                    imageTarget.setVisibility(View.GONE);
//                                    mVideoTarget.setVisibility(View.GONE);
//                                    imageVideo.setVisibility(View.GONE);
//                                    mScoreTarget.setVisibility(View.VISIBLE);
//                                    mScoreTarget.setImageBitmap(ImageUtil.stringToBitmap(laserShootDataVoData.getImitate_image()));
//                                    mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(laserShootDataVoData.getImage()));
                                }
                                //视频靶
                                else if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
                                    changeImgStatus();
//                                    imageTarget.setVisibility(View.GONE);
//                                    mScoreTarget.setVisibility(View.GONE);
//                                    imageVideo.setVisibility(View.GONE);
//                                    mVideoTarget.setVisibility(View.VISIBLE);
//                                    mScoreTarget.setImageBitmap(ImageUtil.stringToBitmap(laserShootDataVoData.getImitate_image()));
//                                    mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(laserShootDataVoData.getImage()));
                                }
                                //
                                mListScores.setFocusable(true);
                                mListScores.setFocusableInTouchMode(true);//启用点击
                                mListScores.requestLayout();//刷新
                                mAdapter.setNewData(mShootDataVos);//设置数据集
                                mListScores.scrollToPosition(mAdapter.getItemCount() - 1);//自动滚动到底部

                                BigDecimal laserScore = new BigDecimal(laserShootDataVoData.getPointI().getScore());
                                //是否开启记弹(暂时不写)
                                if (0.0 == laserScore.doubleValue()) {
                                    mSystemTTS.playText(getString(R.string.tts_miss_the_target), "default");
                                } else if (10.0 <= laserScore.doubleValue()) {
                                    mSystemTTS.playText(StrUtil.Format(laserShootDataVoData.getPointI().getScore()) + getString(R.string.tts_ring), "default");
                                } else {
                                    mSystemTTS.playText(StrUtil.Format(laserShootDataVoData.getPointI().getScore()) + getString(R.string.tts_ring) + laserShootDataVoData.getPointI().getOrientation(), "default");
                                }
                                LogUtil.info("---激光报靶时间---" + (System.currentTimeMillis() - runtime));
                            }
                            break;
                        case 27://激光模拟报靶-开始
                            mLaserAllSrore = 0;//激光模拟射击总环数清空
                            //清空状态
                            results.clear();
                            mShootDataVos.clear();
                            mAdapter.setNewData(mShootDataVos);
                            //获取数据
                            ShootingDataVo shootingLaserDataVo = gson.fromJson(str, ShootingDataVo.class);
                            mTvUserName.setText(shootingLaserDataVo.getData().getGroupName());
                            mValueUserName.setText("   " + shootingLaserDataVo.getData().getPeopleName());
                            SPUtils.getInstance().put("RaceId", shootingLaserDataVo.getData().getRace_id());
                            SPUtils.getInstance().put("GroupId", shootingLaserDataVo.getData().getGroup_id());
                            SPUtils.getInstance().put("PeopleId", shootingLaserDataVo.getData().getPeople_id());
//                            if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
//
//                            }
                            mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(shootingLaserDataVo.getData().getImage()));
                            mScoreTarget.setImageResource(R.mipmap.target_chest_circle);
                            mTvShootState.setText(getString(R.string.tiele_have_in_head));
                            mTvShootState.setTextColor(getResources().getColor(R.color.colorPrimary));
                            mBulletLength = 0;
                            shootingState = 1;
                            break;
                        case 28://激光模拟报靶-结束
                            localDisplayList.add("-----结束-----");
                            mLaserAllSrore = 0;//激光模拟射击总环数清空
                            mTvShootState.setText(getString(R.string.title_not_yet_begun));
                            mTvShootState.setTextColor(getResources().getColor(R.color.red));
                            shootingState = 2;
                            if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
                                String image = object.getString("data");
                                mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(image));
                            }
                            break;
                        case 20://开始
                            //部队换人 -开始
                            //清空记弹器数据集合
                            localDisplayList.add("-----开始-----");
                            mLaserAllSrore = 0;//激光模拟射击总环数清空
                            //清空状态
                            results.clear();
                            mShootDataVos.clear();
                            mAdapter.setNewData(mShootDataVos);
                            mBulletLength = 0;
                            //清除坐标点
                            mPoints.clear();
                            mScoreTarget.setImageResource(R.drawable.bg_canvas);//模拟靶上的点位清空
                            //开始记弹
                            isOpenRecordBullet = true;
                            if (bleConnect) {
                                memorizingBulletsNum.setTextColor(getResources().getColor(R.color.colorPrimary));
                                memorizingBulletsStr.setTextColor(getResources().getColor(R.color.colorPrimary));
                            }
//                            mScoreTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
//                            mVideoTarget.showAllTargets(mPoints, mWidth, mHeight, 1);
                            String data = object.getString("data");
                            ShootingDataVo shootingDataVo = gson.fromJson(str, ShootingDataVo.class);

                            mTvUserName.setText(shootingDataVo.getData().getGroupName());
                            //写死的
                            //mTvUserName.setText("某人1");

                            mValueUserName.setText("   " + shootingDataVo.getData().getPeopleName());
                            SPUtils.getInstance().put("RaceId", shootingDataVo.getData().getRace_id());
                            SPUtils.getInstance().put("GroupId", shootingDataVo.getData().getGroup_id());
                            SPUtils.getInstance().put("PeopleId", shootingDataVo.getData().getPeople_id());
                            if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
                                //替换为下面mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(shootingDataVo.getData().getImage()));
                                handleVideoImg(shootingDataVo.getData().getImage());
                            }

                            mTvShootState.setText(getString(R.string.tiele_have_in_head));
                            mTvShootState.setTextColor(getResources().getColor(R.color.colorPrimary));
                            mBulletLength = 0;
                            shootingState = 1;
//                            if (bleConnect){
//                                patternState = 1;
//                            }
//                            else{
//                                patternState = 2;
//                            }
                            if (!bleConnect && !mRecordingBullet) {
                                tesxs = true;
                                if (mEdDeviceNum.isEnabled()) {
                                    mSystemTTS.playText(getString(R.string.tts_clear_set_target), "default");
                                } else {
                                    initFireTest(0);
                                }
                            }
                            break;
                        case 21:   //修改配置
                            //                        //TODO   消息处理不完全
                            //是否精确报靶
                            String data1 = object.getString("data");
                            ShootingDataVo shootingDataVo1 = gson.fromJson(str, ShootingDataVo.class);

                            bullet_num_today = shootingDataVo1.getData().isEnable_circle_float();
                            //开枪时间间隔
                            mDefaultFireTime = shootingDataVo1.getData().getBluetooth_time_threshold();
                            //升压值
                            mDefaultSound = shootingDataVo1.getData().getBluetooth_voice_threshold();
                            //开枪接口延迟延迟
                            mCameraCaptureDelay = shootingDataVo1.getData().getCamera_capture_delay();
                            //模式切换
                            if (!shootingDataVo1.getData().getShoot_env().equals(SPUtils.getInstance().getString("env"))) {
                                SPUtils.getInstance().put("env", shootingDataVo1.getData().getShoot_env());
                            }
                            break;
                        case 22:   //部队结束射击
                            localDisplayList.add("-----结束-----");
                            mLaserAllSrore = 0;//激光模拟射击总环数清空
                            mTvShootState.setText(getString(R.string.title_not_yet_begun));
                            mTvShootState.setTextColor(getResources().getColor(R.color.red));

                            //清空list-
                            results.clear();
                            mShootDataVos.clear();
                            mAdapter.setNewData(mShootDataVos);
                            mBulletLength = 0;
                            //不记弹
                            isOpenRecordBullet = false;
                            startNewRound();//重置记弹器逻辑

                            //记弹器归零并设置颜色
                            ActualNumberOfBulletsRecorded = 0;
                            if (bleConnect) {
                                memorizingBulletsNum.setText(ActualNumberOfBulletsRecorded.toString());
                                memorizingBulletsNum.setTextColor(Color.BLACK);
                                memorizingBulletsStr.setTextColor(Color.BLACK);
                            }
                            //清除坐标点
                            mPoints.clear();
//                            mScoreTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
//                            mVideoTarget.showAllTargets(mPoints, mWidth, mHeight, 1);
                            if (!bleConnect && !mRecordingBullet) {
                                tesxs = false;
                            }
                            shootingState = 2;
//                            patternState = 0;
//                            if (timer!=null){
//                                timer.cancel();
//                                timer = null;
//                            }
//                            if (task!=null){
//                                task.cancel();
//                                task = null;
//                            }
//                            Log.e("-=-=-=-=-=-=-=task","|||||||||||||||||||||||||||");
//                            try {
//                                String image = object.getString("data");
//                                if (image != null && !image.equals("")) {
//                                    String replace = image.replace("C:\\shoot-data\\", "");
//                                    imageAddress = replace;
//                                }
//                                if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
//                                    GlideUtils.getInstance().loadImage(MainActivity.this, UrlHelper.IMAGE + imageAddress, imageVideo);
//                                }
//                            } catch (Exception e) {
//
//                            }
//                            if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {

                            String images = object.getString("data");
                            if (rbtnSim.getText().toString().equals(getString(R.string.rb_simulation_target))) {
                                /**
                                 * /模拟靶逻辑
                                 */
                                imageTarget.setVisibility(View.GONE);
                                mVideoTarget.setVisibility(View.GONE);//视频靶
                                imageVideo.setVisibility(View.GONE);
                                mScoreTarget.setVisibility(View.VISIBLE);//实图靶
                                mScoreTarget.setImageResource(R.drawable.bg_canvas);//模拟靶上的点位清空
                            } else if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
                                /**
                                 * 实图靶
                                 */
                                imageTarget.setVisibility(View.GONE);
                                mScoreTarget.setVisibility(View.GONE);
                                imageVideo.setVisibility(View.GONE);
                                mVideoTarget.setVisibility(View.VISIBLE);
                                Glide.with(MainActivity.this)
                                        .load(R.mipmap.target_chest_circle_video)
                                        .into(mVideoTarget);
                            }
//                            }
                            break;
                        case 30:
                            //上传振动值
                            initUpdatasensorlist();
                            break;
                        case 31:
                            //服务器下发的阈值
                            String data2 = object.getString("data");
                            ShootingDataVo shootingDataVo2 = gson.fromJson(str, ShootingDataVo.class);
                            vibrationValue = shootingDataVo2.getData().getPressure();
                            SPUtils.getInstance().put("vibrationValue", vibrationValue);
                            break;
                        //模式  是否记弹   图片标注
                        case 3001:
                            if (!mTvShootState.getText().toString().equals(getString(R.string.title_not_yet_begun))) {
                                return;
                            } else {
                                String type = object.getString("data");
                                LogUtil.error("type--" + type);
                                try {
                                    JSONObject jsonObject = new JSONObject(type);
                                    Iterator<String> keys = jsonObject.keys();
                                    mRealGraph = false;
                                    mRecordingBullet = false;
                                    mSimulation = false;
                                    while (keys.hasNext()) {
                                        // 获得key
                                        String key = keys.next();
                                        String teamsInfo = jsonObject.optString(key);
                                        if (Integer.valueOf(teamsInfo) == 1) {
                                            mSimulation = true;
                                        } else if (key.equals("智能集成")) {

                                        } else if (Integer.valueOf(teamsInfo) == 2) {
                                            mRealGraph = true;
                                        } else if (Integer.valueOf(teamsInfo) == 3) {
                                            mRecordingBullet = true;
                                        }
                                    }

                                    if (mRecordingBullet) {
                                        if (!bleConnect && !mLaserBullet) {
                                            mSystemTTS.playText("请连接计蛋器，否则无法记蛋", "default");
                                        }
                                    } else {
                                        if (bleConnect) {
                                            toBreakOff = true;
                                            mIsAccordUnbind = true;
                                            mService.disconnect();
                                            mServiceUART.disconnect();
                                        }
                                    }
                                    LogUtil.error("mSimulation-" + mSimulation + "---mRealGraph-" + mRealGraph + "---mRecordingBullet-" + mRecordingBullet);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            break;
                        //更换靶纸
                        case 10000:
//                            if (data.getResults().get(data.getResults().size() - 1).getAll_points()
//                                    .get(data.getResults().get(data.getResults().size() - 1).getAll_points().size() - 1).getCut_path() != null) {
//                                String replace = data.getResults().get(data.getResults().size() - 1).getAll_points()
//                                        .get(data.getResults().get(data.getResults().size() - 1).getAll_points().size() - 1).getCut_path().replace("C:\\shoot-data\\", "");
//                                imageAddress = replace;
//                            }
//                            String image = object.getString("data");
                            if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
                                String image = object.getString("data");
                                mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(image));
                                handleVideoImg(image);
                            }

                            break;
//                        case 10002:
//
//                            String datas = object.getString("data");

                        case 100001://---------ZJH---------
                            if (DialogControl) {//判断是否绑定靶位了

//                            Object objects = object.get("data");
                                //从Socket中获取需要用的Json数据
                                String datas = object.getString("data");
                                //将获取的Json数据转化为实体类
                                ShootFireDataTestVo dataJibo = gson.fromJson(datas, ShootFireDataTestVo.class);
//                            ShootFireDataTestVo dataJibo = (ShootFireDataTestVo) object.get("data");
                                //判断实体类中的点位集合不为空
                                if (dataJibo.getResults() != null && dataJibo.getResults().size() != 0) {
//                                    imageAddress = data.getAll_points().get(data.getAll_points().size() - 1).getImage();
                                    //获取最新一个点位的图片
                                    String cutPath = dataJibo.getResults().get(dataJibo.getResults().size() - 1).getAll_points()
                                            .get(dataJibo.getResults().get(dataJibo.getResults().size() - 1).getAll_points().size() - 1).getCut_path();

                                    if (cutPath != null) {
                                        //ZJH--add
                                        wsImgAddress = cutPath;
                                        //将获取到的图片进行处理
                                        String replace = cutPath.replace("C:\\shoot-data\\", "");
                                        imageAddress = replace;
                                    }
//                                LogUtil.FileLog(System.currentTimeMillis()+" 请求回来，对数据进行处理");
                                    //设置
                                    //清空点位
                                    mPoints.clear();
                                    //清空子弹表
                                    mShootDataVos.clear();
                                    mAdapter.setNewData(mShootDataVos);
                                    //清空分数
                                    mAllSrore = 0;
                                    //建立集合用来存储所有点位
                                    List<ShootFireVo> all_points1 = new ArrayList<>();

                                    results = dataJibo.getResults();
                                    //靶纸id不同时更换paper  部队模式   俱乐部模式在更换靶纸接口清除paper
                                    //存储的靶纸如果存在、所有射击记录不为空、存储的靶纸跟获取的靶纸不一样
                                    if (paper != null && results.get(results.size() - 1).getAll_points() != null && results.get(results.size() - 1).getAll_points().size() != 0
                                            && paper.getPaper_id() != results.get(results.size() - 1).getAll_points().get(results.get(results.size() - 1).getAll_points().size() - 1).getPaper_id()) {
                                        //将存在的靶纸置空
                                        paper = null;
                                    }
                                    //查看是模拟靶还是视频靶
                                    if (rbtnSim.getText().toString().equals(getString(R.string.rb_simulation_target))) {
                                        /**
                                         * /模拟靶逻辑
                                         */
                                        all_points1 = getSimulation(results);
                                    } else if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
                                        /**
                                         * 实图靶
                                         */
                                        all_points1 = getRealGraph(results);

//                                    LogUtil.FileLog("imageAddress:  "+imageAddress);
                                        if (imageAddress != null && !imageAddress.equals("")) {
                                            if (mRecordingBullet) {
                                                GlideUtils.getInstance().loadImage(MainActivity.this, UrlHelper.IMAGE + imageAddress, imageVideo);
                                            } else if (!mRecordingBullet && (all_points1.get(all_points1.size() - 1).getScore() != 0.0 || all_points1.get(all_points1.size() - 1).getAngel() != 0)) {
                                                GlideUtils.getInstance().loadImage(MainActivity.this, UrlHelper.IMAGE + imageAddress, imageVideo);
                                            }
                                        }
                                    }
                                    //如果传-1就结束射击
                                    if (-1.0 == all_points1.get(all_points1.size() - 1).getScore()) {
                                        all_points1.remove(all_points1.size() - 1);
                                        return;
                                    }
                                    //填充数据
                                    fillNewData(all_points1);
                                    mScoreTarget.setImageBitmap(loadPointTargetImage(all_points1));

                                    //不同靶不同数据填充
                                    if (rbtnSim.getText().toString().equals(getString(R.string.rb_simulation_target))) {
                                        //模拟靶逻辑
                                        changeImgStatus();//ZJH--add
//                                    imageTarget.setVisibility(View.GONE);
//                                    mVideoTarget.setVisibility(View.GONE);
//                                    imageVideo.setVisibility(View.GONE);
//                                    mScoreTarget.setVisibility(View.VISIBLE);
//                                    mScoreTarget.setImageBitmap(ImageUtil.stringToBitmap(dataJibo.getImg_path2()));
//                                    mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(dataJibo.getImg_path()));

//                                        mScoreTarget.setTranslate(mWidth * 0.5, mHeight * 0.5965483555845002);
//                                        mScoreTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
                                    } else if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
                                        /**
                                         * 实图靶
                                         */
                                        changeImgStatus();//ZJH--add
                                    }


                                    mListScores.setFocusable(true);
                                    mListScores.setFocusableInTouchMode(true);

                                    mListScores.requestLayout();
                                    //记弹数改颜色以及数量
//                                memorizingBulletsNum.setTextColor(getResources().getColor(R.color.colorPrimary));
//                                memorizingBulletsStr.setTextColor(getResources().getColor(R.color.colorPrimary));
//                                memorizingBulletsNum.setText(mShootDataVos.size() + "");
                                    mAdapter.setNewData(mShootDataVos);
                                    mListScores.scrollToPosition(mAdapter.getItemCount() - 1);

                                    if (mRecordingBullet && false) {
                                        float score = (float) 0.0;
                                        if (mShootDataVos != null && mShootDataVos.size() != 0) {
                                            score = mShootDataVos.get(mShootDataVos.size() - 1).getScore();
                                            BigDecimal bigDecimalScore = new BigDecimal(score);
                                            if (0.0 == bigDecimalScore.doubleValue()) {
                                                mSystemTTS.playText(getString(R.string.tts_miss_the_target), "default");
                                            } else if (10.0 == bigDecimalScore.doubleValue()) {
                                                if (bullet_num_today) {
                                                    mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring), "default");
                                                } else {
                                                    mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring), "default");
                                                }

                                            } else if (-1.0 == bigDecimalScore.doubleValue()) {

                                            } else {
                                                if (bullet_num_today) {
                                                    //mSystemTTS.playText(score + getString(R.string.tts_ring) + mShootDataVos.get(mShootDataVos.size() - 1).getOrientation(), "default");
                                                    mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring), "default");

                                                } else {
                                                    //mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring) + mShootDataVos.get(mShootDataVos.size() - 1).getOrientation(), "default");
                                                    mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring), "default");

                                                }
                                            }
                                        }

//                                } else if (!mRecordingBullet && mShootDataVos != null && mShootDataVos.size() != 0
                                    } else if (true && mShootDataVos != null && mShootDataVos.size() != 0
                                            && mShootDataVos.get(mShootDataVos.size() - 1).getAngel() != 0 && mBulletLength != mShootDataVos.size()) {
                                        float score = (float) 0.0;
                                        if (mShootDataVos != null && mShootDataVos.size() != 0) {
                                            score = mShootDataVos.get(mShootDataVos.size() - 1).getScore();
                                        }
                                        if (score != 0.0) {
                                            BigDecimal bigDecimalScore = new BigDecimal(score);
                                            if (0.0 == bigDecimalScore.doubleValue()) {
//                                                mSystemTTS.playText(getString(R.string.tts_miss_the_target), "default");
                                            } else if (10.0 == bigDecimalScore.doubleValue()) {
                                                if (bullet_num_today) {
                                                    mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring), "default");
                                                } else {
                                                    mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring), "default");
                                                }

                                            } else if (-1.0 == bigDecimalScore.doubleValue()) {

                                            } else {
                                                if (bullet_num_today) {
                                                    // mSystemTTS.playText(score + getString(R.string.tts_ring) + mShootDataVos.get(mShootDataVos.size() - 1).getOrientation(), "default");
                                                    mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring), "default");

                                                } else {
                                                    // mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring) + mShootDataVos.get(mShootDataVos.size() - 1).getOrientation(), "default");
                                                    mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring), "default");
                                                }
                                            }
                                        } else if (score == 0.0 && mShootDataVos.get(mShootDataVos.size() - 1).getAngel() != 0) {
                                            mSystemTTS.playText(getString(R.string.tts_miss_the_target), "default");
                                        }
                                    }
                                    mBulletLength = mShootDataVos.size();

                                    // mAdapter.setNewData(mShootDataVos);
                                    //滚到最后一行
//                                    Toast.makeText(MainActivity.this, "-----", Toast.LENGTH_SHORT).show()

                                } else {
                                    LogUtil.error("-----" + "请求成功--数据为空");
                                }
                            }
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                //soceket握手和心跳情况打印
            case EventBusCode.DEBUG_SOCKET:
                socketList.add(TimeUtils.getTime() + (String) center.getData());
                if (socketDialog != null && socketDialog.isShowing()) {
                    socketDialog.setListRefresh(socketList);
                }
                break;
        }
    }

//    new Thread(new Runnable() {
//        @Override
//        public void run() {
//            try {
//                for (int i = 0; i < 10; i++) {
//                    initFireTest(0);
//                    Thread.sleep(500);
//                }
//            } catch (InterruptedException e) {
//
//            }
//        }
//    }).start();

    SocketDialog socketDialog;

    private BlueListDialog blueListDialog;

    private Map<String, String> fileMap = new HashMap<>();

    /**
     * 写入文件----目前没用
     *
     * @param message
     */
    @Deprecated
    private void initFile(String message) {
        try {
            String time = TimeUtils.getTime();
            fileMap.put(time, message);
            Gson gson = new Gson();
            String s = gson.toJson(fileMap);
            fileMap.clear();
            FileOutputStream fileOutputStream = MainActivity.this.openFileOutput(TimeUtils.getYear() + "年" + TimeUtils.getYear() + "月" +
                    TimeUtils.getDay() + "日" + ".txt", Context.MODE_APPEND + Context.MODE_PRIVATE);
            byte[] bytes = s.getBytes();
            fileOutputStream.write(bytes);
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 切换靶纸
     */
    private void switchUnknwn() {
        if (mEdDeviceNum.isEnabled()) {
            //正在输入.点击了完成。
            String num = mEdDeviceNum.getText().toString().trim();
            //向服务单请求能否设置该机位。
            mScoreTarget.post(new Runnable() {
                @Override
                public void run() {
                    mWidth = mScoreTarget.getWidth();
                    mHeight = mScoreTarget.getHeight();
                    requestShootDeviceIdFromServerTest(num);
                }
            });
        } else {
            //点击了设置。
            SPUtils.getInstance().put("Shooting", false);
            initSetBt(false);
            //清除数据
            mShootDataVos.clear();
            mAdapter.setNewData(mShootDataVos);
            //清除坐标点
            mPoints.clear();
//            mScoreTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
            mScoreTarget.setImageDrawable(getDrawable(R.drawable.bg_canvas));
        }
    }

    //视频靶 模拟靶切换
    private void initImage() {
        if (rbtnSim.getText().equals(getString(R.string.rb_simulation_target))) {
            rbtnSim.setText(getString(R.string.rb_video_target));
            mPoints.clear();
            changeImgStatus();
//            imageTarget.setVisibility(View.GONE);
//            mScoreTarget.setVisibility(View.GONE);
//            imageVideo.setVisibility(View.GONE);
//            mVideoTarget.setVisibility(View.VISIBLE);
//            mVideoTarget.setGreenTargetWidth(32);
//            mVideoTarget.setRedTargetWidth(38);
            //设置坐标系
            if (results != null) {
                fillNewData(getRealGraph(results));
            }
            setTargetCore(results);
            if (imageAddress != null && !imageAddress.equals("")) {
                GlideUtils.getInstance().loadImage(MainActivity.this, UrlHelper.IMAGE + imageAddress, imageVideo);
            }
//            mVideoTarget.showAllTargets(mPoints, mWidth, mHeight, 1);
        } else if (rbtnSim.getText().equals(getString(R.string.rb_video_target))) {
            mPoints.clear();
            rbtnSim.setText(getString(R.string.rb_simulation_target));
            changeImgStatus();
//            imageTarget.setVisibility(View.GONE);
//            mScoreTarget.setVisibility(View.VISIBLE);
//            mVideoTarget.setVisibility(View.GONE);
//            imageVideo.setVisibility(View.GONE);
            //设置坐标系
//            mScoreTarget.setTranslate(mWidth * 0.5, mHeight * 0.5965483555845002);
            fillNewData(getSimulation(results));
//            mScoreTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
        }
    }

    /**
     * 注册射击位-目前没用
     * .setSupportsChangeAnimations(false)
     *
     * @param shootingNum 射击位
     */
    private void requestShootDeviceIdFromServer(String shootingNum) {
        if (!shootingNum.isEmpty()) {
            OkGo.<WhResponse<ShootRegisterVo>>post(UrlHelper.BASE + UrlHelper.
                            SETTING_TARGET_POSITION)
                    .params("number", shootingNum)
                    .params("client_ip", NetWorkUtils.getLocalIpAddress(this))
                    .params("client_width", mWidth)
                    .params("client_height", mHeight)
                    .execute(new DialogCallback<WhResponse<ShootRegisterVo>>(this) {
                        @Override
                        public void onSuccess(Response<WhResponse<ShootRegisterVo>> response) {
                            LogUtil.error("====" + response.code());
                            DialogControl = true;
                            //姓名
                            if (response.body().data.getPeople_name() != null && !response.body().data.getPeople_name().equals("")) {
                                mPeopleName = response.body().data.getPeople_name();
                            } else {
                                mPeopleName = getString(R.string.title_no_state_at_all);
                            }
                            //批次
                            if (response.body().data.getRace_id() != 0) {
                                SPUtils.getInstance().put("RaceId", response.body().data.getRace_id());
                            }
                            //组id
                            if (response.body().data.getGroup_id() != 0) {
                                SPUtils.getInstance().put("GroupId", response.body().data.getGroup_id());
                            }

                            //记录射击位
                            SPUtils.getInstance().put("ShootingNum", shootingNum);
                            switch (response.body().code) {
                                case 0:
                                    ShootRegisterVo data = response.body().data;
                                    //视频靶
                                    if (response.body().data.getImage() != null && !response.body().data.getImage().equals("") && imageVideo.getVisibility() == View.GONE) {
                                        imageAddress = response.body().data.getImage();
                                    }
                                    //保存状态
                                    bullet_num_today = data.getEnable_circle_float();
                                    if (!"0".equals(data.getPaper_id() + "")) {
                                        SPUtils.getInstance().put("PagerId", data.getPaper_id());
                                    }
                                    if (!"0".equals(data.getPeople_id() + "")) {
                                        SPUtils.getInstance().put("PeopleId", data.getPeople_id());
                                    }
                                    SPUtils.getInstance().put("Shooting", false);
                                    initSetBt(true);

//                                    Log.e("ble", "执行否");
//                                    mScoreTarget.setTranslate(mWidth * 0.5, mHeight * 0.5965483555845002);
                                    if (null == data.getRecords() && null == data.getRecords().getAll_points() || data.getRecords().getAll_points().size() == 0) {
                                        //    为空的情况
                                        mPoints.clear();
                                        mShootDataVos.clear();
                                        mAllSrore = 0;
                                        mAdapter.setNewData(mShootDataVos);
//                                        mScoreTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
                                        //  mListScores.scrollToPosition(mAdapter.getItemCount() - 1);
                                    } else { //不为空的情况
                                        mPoints.clear();
                                        mShootDataVos.clear();
                                        mAllSrore = 0;

                                        for (ShootFireVo shootAllDataVo : data.getRecords().getAll_points()) {
                                            mAllSrore += shootAllDataVo.getScore();
                                            //设置虚拟靶位坐标
                                            mPoints.add(new Point(shootAllDataVo.getX(), shootAllDataVo.getY()));
                                            //绑定新数据
                                            mShootDataVos.add(new ShootFireVo(shootAllDataVo.getScore(), shootAllDataVo.getOrientation(), shootAllDataVo.getAngel(),
                                                    shootAllDataVo.getX(), shootAllDataVo.getY(), shootAllDataVo.getImage(), shootAllDataVo.isEnable_circle_float(), mAllSrore, shootAllDataVo.getTarget_type()));
                                            EnableCircleFloat = shootAllDataVo.isEnable_circle_float();
                                        }
                                        mAdapter.setNewData(mShootDataVos);
//                                        mScoreTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
                                        mListScores.scrollToPosition(mAdapter.getItemCount() - 1);
                                    }
                                    //切换部队俱乐部
                                    if ("army".equals(data.getEnv())) {
                                        //部队
                                        mClearAll.setVisibility(View.GONE);
                                        mClearLocal.setVisibility(View.GONE);
                                        mFire.setVisibility(View.GONE);
                                        mFab.setVisibility(View.GONE);
                                        mTvUserName.setVisibility(View.VISIBLE);
                                        mValueUserName.setVisibility(View.VISIBLE);
                                        mValueUserName.setText("   " + mPeopleName);
                                        btSound.setVisibility(View.VISIBLE);
                                    } else {
                                        //俱乐部
                                        mClearAll.setVisibility(View.INVISIBLE);
                                        mClearLocal.setVisibility(View.INVISIBLE);
                                        mFire.setVisibility(View.INVISIBLE);
                                        mFab.setVisibility(View.VISIBLE);
                                        mTvUserName.setVisibility(View.INVISIBLE);
                                        mValueUserName.setVisibility(View.INVISIBLE);
                                        btSound.setVisibility(View.VISIBLE);
                                    }
                                    break;
                                default:
                                    //相机连接不到;
                                    initSetBt(false);
                                    mSystemTTS.playText(response.body().msg, "default");
                                    break;
                            }
                        }

                        @Override
                        public void onError(Response<WhResponse<ShootRegisterVo>> response) {
                            super.onError(response);
                            initSetBt(false);
                            LogUtil.error("-----" + "请求失败" + response.getException().toString());

                        }
                    });


        } else {
            ToastUtils.show(R.string.tos_clear_set_target);
        }
    }

    /**
     * 注册靶位 真实靶位测试
     */
    private void requestShootDeviceIdFromServerTest(String shootingNum) {
        OkGo.<WhResponse<RegistertestVo>>post(UrlHelper.BASE + UrlHelper.SETTING_TAGET_POSITION_registertest)
                .params("number", shootingNum)
                .params("client_ip", NetWorkUtils.getLocalIpAddress(this))
                .params("client_width", mWidth)
                .params("client_height", mHeight)
                .execute(new DialogCallback<WhResponse<RegistertestVo>>(this) {
                    @Override
                    public void onSuccess(Response<WhResponse<RegistertestVo>> response) {
                        mLaserBullet = false;
                        RegistertestVo data1 = response.body().data;
                        if (data1.getType() == null) {
                            mSystemTTS.playText("请在后台选择训练类型", "default");
                            return;
                        }
                        if (response.body().code == 0 && data1 != null) {
                            DialogControl = true;
                            //姓名
                            if (data1.getPeople_name() != null && !data1.getPeople_name().equals("")) {
                                mPeopleName = data1.getPeople_name();
                            } else {
                                mPeopleName = getString(R.string.title_no_state_at_all);
                            }
                            //批次
                            if (data1.getRace_id() != 0) {
                                SPUtils.getInstance().put("RaceId", data1.getRace_id());
                            }
                            //组id
                            if (data1.getGroup_id() != 0) {
                                SPUtils.getInstance().put("GroupId", data1.getGroup_id());
                            }

                            if (data1.getType() != null) {
                                String type = data1.getType().toString();
                                LogUtil.error("type--" + type);
                                try {
                                    JSONObject jsonObject = new JSONObject(type);
                                    Iterator<String> keys = jsonObject.keys();
                                    mSimulation = false;
                                    mRealGraph = false;
                                    mRecordingBullet = false;
                                    while (keys.hasNext()) {
                                        // 获得key
                                        String key = keys.next();
                                        if (key.equals("模拟报靶")) {
                                            mSimulation = true;
                                        } else if (key.equals("智能集成")) {

                                        } else if (key.equals("视频报靶")) {
                                            mRealGraph = true;
                                        } else if (key.equals("计弹")) {
                                            mRecordingBullet = true;
                                        } else if (key.equals("激光报靶")) {
                                            mLaserBullet = true;
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            mShootingNum = shootingNum;
                            //初始化气象定时器
                            if (meteorologicalTimer == null) {
                                meteorologicalTimer = new Timer();
                                //启动气象定时任务
                                initMeteorologicalMonitor(meteorologicalTimer);
                            }

                            SPUtils.getInstance().put("ShootingNum", shootingNum);
                            switch (response.body().code) {
                                case 0:
                                    //射击中
                                    if (data1.getShoot() == 1) {
                                        shootingState = 1;
                                        if (!mRecordingBullet) {
//                                            patternState = 2;
                                            tesxs = true;
                                            if (mEdDeviceNum.isEnabled()) {
                                                mSystemTTS.playText(getString(R.string.tts_clear_set_target), "default");
                                            } else {
                                                initFireTest(0);
                                            }
                                            mTvShootState.setText(getString(R.string.tiele_have_in_head));
                                            mTvShootState.setTextColor(getResources().getColor(R.color.colorPrimary));
                                        }
                                    }
                                    //结束射击
                                    else {
                                        shootingState = 2;
                                        mTvShootState.setText(getString(R.string.title_not_yet_begun));
                                        mTvShootState.setTextColor(getResources().getColor(R.color.red));
                                    }

                                    //视频靶
                                    if (data1.getRecords() != null) {
//                                        if (response.body().data.getImage() != null && !response.body().data.getImage().equals("")) {
//                                            String replace = response.body().data.getImage().replace("C:\\shoot-data\\", "");
//                                            imageAddress = replace;
//                                        }
//                                        if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
//                                            GlideUtils.getInstance().loadImage(MainActivity.this, UrlHelper.IMAGE + imageAddress, imageVideo);
//                                        }
//                                        mScoreTarget.setImageBitmap(ImageUtil.stringToBitmap(data.getImage()))
                                        //需要标点。
                                        mScoreTarget.setImageResource(R.mipmap.target_chest_circle);
                                        if (NotNullHelper.notEmpty(data1.getImage())) {
                                            //废弃mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(data1.getImage()));
                                            handleVideoImg(data1.getImage());
                                        }

                                        //保存状态
                                        bullet_num_today = data1.isEnable_circle_float();
                                        if (!"0".equals(data1.getPaper_id() + "")) {
                                            SPUtils.getInstance().put("PagerId", data1.getPaper_id());
                                        }
                                        if (!"0".equals(data1.getPeople_id() + "")) {
                                            SPUtils.getInstance().put("PeopleId", data1.getPeople_id());
                                        }

                                        SPUtils.getInstance().put("Shooting", true);

                                        initSetBt(true);
                                        //是否为激光模拟报靶
                                        if (data1.getRecords().getResults().size() == 0 && mLaserBullet) {

                                            //切换部队俱乐部
                                            if ("army".equals(data1.getEnv())) {
                                                //部队
                                                mClearAll.setVisibility(View.GONE);
                                                mClearLocal.setVisibility(View.GONE);
                                                mFire.setVisibility(View.GONE);
                                                mFab.setVisibility(View.GONE);
                                                mTvUserName.setVisibility(View.VISIBLE);
                                                mValueUserName.setVisibility(View.VISIBLE);
                                                mValueUserName.setText("   " + mPeopleName);
                                                btSound.setVisibility(View.VISIBLE);
                                            } else {
                                                //俱乐部
                                                mClearAll.setVisibility(View.INVISIBLE);
                                                mClearLocal.setVisibility(View.INVISIBLE);
                                                mFire.setVisibility(View.INVISIBLE);
                                                mFab.setVisibility(View.VISIBLE);
                                                mTvUserName.setVisibility(View.INVISIBLE);
                                                mValueUserName.setVisibility(View.INVISIBLE);
                                                btSound.setVisibility(View.VISIBLE);
                                            }
                                            //激光模拟报靶(没有成绩)
                                            mScoreTarget.setImageResource(R.mipmap.target_chest_circle);
                                            //废弃mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(data1.getImage()));
                                            handleVideoImg(data1.getImage());
                                            initSetBt(true);
                                            btBlueModify.setEnabled(false);//激光模拟报靶禁用记弹器
                                            mSystemTTS.playText("当前为激光模拟训练，不支持记蛋器", "default");
                                            return;
                                        } else {
                                            btBlueModify.setEnabled(true);//激光模拟报靶禁用记弹器
                                            mSystemTTS.playText("当前为实弹训练，支持记蛋器", "default");
                                        }
                                        //实弹报靶逻辑
                                        if (null == data1.getRecords() || null == data1.getRecords().getResults() || data1.getRecords().getResults().size() == 0) {
                                            //    为空的情况
                                            mPoints.clear();
                                            mShootDataVos.clear();
                                            mAllSrore = 0;
                                            mAdapter.setNewData(mShootDataVos);
//                                            mScoreTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
//                                            mVideoTarget.showAllTargets(mPoints, mWidth, mHeight, 1);
                                            //  mListScores.scrollToPosition(mAdapter.getItemCount() - 1);
                                        } else { //不为空的情况
                                            mPoints.clear();
                                            mShootDataVos.clear();
                                            mAllSrore = 0;

                                            List<ShootFireVo> all_points1 = new ArrayList<>();
                                            results = data1.getRecords().getResults();
                                            String image = data1.getImage();
                                            if (rbtnSim.getText().toString().equals(getString(R.string.rb_simulation_target))) {
                                                /**
                                                 * /模拟靶逻辑
                                                 */
                                                changeImgStatus();
                                                all_points1 = getSimulation(results);

//                                                mScoreTarget.setImageBitmap(ImageUtil.stringToBitmap(image));
//                                                mScoreTarget.setImageResource(R.mipmap.target_chest_circle);
//                                                mScoreTarget.setTranslate(mWidth * 0.5, mHeight * 0.5965483555845002);
                                            } else if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
                                                /**
                                                 * 实图靶
                                                 */
                                                all_points1 = getRealGraph(results);
                                                //坐标系中心点  实图靶修改
                                                setTargetCore(results);
                                                //废弃mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(image));
                                                handleVideoImg(image);
                                            }

                                            //填充数据
                                            fillNewData(all_points1);
                                            mBulletLength = mShootDataVos.size();
                                            memorizingBulletsNum.setText(mBulletLength + "");
                                            mAdapter.setNewData(mShootDataVos);
                                            mListScores.scrollToPosition(mAdapter.getItemCount() - 1);
                                            mScoreTarget.setImageBitmap(loadPointTargetImage(all_points1));
                                            //不同靶不同数据填充
                                            if (rbtnSim.getText().toString().equals(getString(R.string.rb_simulation_target))) {
                                                /**
                                                 * /模拟靶逻辑
                                                 */
//                                                mScoreTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
                                                //mScoreTarget.setImageResource(R.mipmap.target_chest_circle);
//                                                mScoreTarget.setImageBitmap(ImageUtil.stringToBitmap(data.getImage()));
                                            } else if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
                                                /**
                                                 * 实图靶   注册暂不标记
                                                 */
//                                                mVideoTarget.showAllTargets(new ArrayList<Point>(), mWidth, mHeight, 1);
                                                //废弃mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(data1.getImage()));
                                                handleVideoImg(data1.getImage());
                                            }
                                        }
                                        ;
                                        //切换部队俱乐部
                                        if ("army".equals(data1.getEnv())) {
                                            //部队
                                            mClearAll.setVisibility(View.GONE);
                                            mClearLocal.setVisibility(View.GONE);
                                            mFire.setVisibility(View.GONE);
                                            mFab.setVisibility(View.GONE);
                                            mTvUserName.setVisibility(View.VISIBLE);
                                            mValueUserName.setVisibility(View.VISIBLE);
                                            mValueUserName.setText("   " + mPeopleName);
                                            btSound.setVisibility(View.VISIBLE);
                                        } else {
                                            //俱乐部
                                            mClearAll.setVisibility(View.INVISIBLE);
                                            mClearLocal.setVisibility(View.INVISIBLE);
                                            mFire.setVisibility(View.INVISIBLE);
                                            mFab.setVisibility(View.VISIBLE);
                                            mTvUserName.setVisibility(View.INVISIBLE);
                                            mValueUserName.setVisibility(View.INVISIBLE);
                                            btSound.setVisibility(View.VISIBLE);
                                        }
                                    }
                                    break;
                            }
                        }
                    }

                    @Override
                    public void onError(Response<WhResponse<RegistertestVo>> response) {
                        super.onError(response);
                    }
                });
    }

    /**
     * 开枪接口  TODO  实图报靶
     */
    private void initFireTest(long zd) {

        long runTime = System.currentTimeMillis();

        OkGo.<WhResponse<ShootFireDataTestVo>>post(UrlHelper.BASE + UrlHelper.SETTING_TARGET_POSITION_FIRE_test)
                .params("number", mShootingNum)
                .params("paper_id", initSpPagerId())
                .params("people_id", initSpPeopleId())
                .params("race_id", initSpRace_Id())
                .params("group_id", initSpGroup_Id())
                .params("vab_value", zd)
                .params("fire_time", TimeUtils.getTimeStamp())
                .execute(new JsonCallback<WhResponse<ShootFireDataTestVo>>() {
                    @Override
                    public void onSuccess(Response<WhResponse<ShootFireDataTestVo>> response) {
                        Long start_success = System.currentTimeMillis();
                        int debug = 1;
//                        switch (response.body().code) {
                        switch (debug) {
                            case 1:
                                break;
                            case 0:
                                if (tesxs && !mRecordingBullet) {
                                    initFireTest(0);
                                } else if (!tesxs && !mRecordingBullet && false) { //TODO
                                    return;
                                }

                                ShootFireDataTestVo data = response.body().data;
                                if (data.getResults() != null && data.getResults().size() != 0) {
//                                    imageAddress = data.getAll_points().get(data.getAll_points().size() - 1).getImage();
                                    String cutPath = data.getResults().get(data.getResults().size() - 1).getAll_points()
                                            .get(data.getResults().get(data.getResults().size() - 1).getAll_points().size() - 1).getCut_path();
                                    if (cutPath != null) {
                                        //ZJH--add
                                        wsImgAddress = cutPath;
                                        String replace = cutPath.replace("C:\\shoot-data\\", "");
                                        imageAddress = replace;
                                    }
                                    //设置
                                    mPoints.clear();
                                    mShootDataVos.clear();
                                    mAllSrore = 0;

                                    List<ShootFireVo> all_points1 = new ArrayList<>();
                                    results = data.getResults();

                                    //靶纸id不同时更换paper  部队模式   俱乐部模式在更换靶纸接口清除paper
                                    if (paper != null && results.get(results.size() - 1).getAll_points() != null && results.get(results.size() - 1).getAll_points().size() != 0
                                            && paper.getPaper_id() != results.get(results.size() - 1).getAll_points().get(results.get(results.size() - 1).getAll_points().size() - 1).getPaper_id()) {
                                        paper = null;
                                    }
                                    if (rbtnSim.getText().toString().equals(getString(R.string.rb_simulation_target))) {
                                        /**
                                         * 模拟靶逻辑
                                         */
                                        all_points1 = getSimulation(results);
                                    } else if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
                                        /**
                                         * 实图靶
                                         */
                                        all_points1 = getRealGraph(results);

                                        if (imageAddress != null && !imageAddress.equals("")) {
                                            if (mRecordingBullet) {
                                                GlideUtils.getInstance().loadImage(MainActivity.this, UrlHelper.IMAGE + imageAddress, imageVideo);
                                            } else if (!mRecordingBullet && (all_points1.get(all_points1.size() - 1).getScore() != 0.0 || all_points1.get(all_points1.size() - 1).getAngel() != 0)) {
                                                GlideUtils.getInstance().loadImage(MainActivity.this, UrlHelper.IMAGE + imageAddress, imageVideo);
                                            }
                                        }
                                    }


                                    //如果传-1就结束射击
                                    if (-1.0 == all_points1.get(all_points1.size() - 1).getScore()) {
                                        all_points1.remove(all_points1.size() - 1);
                                        return;
                                    }
                                    //填充数据
                                    fillNewData(all_points1);

                                    //不同靶不同数据填充
                                    if (rbtnSim.getText().toString().equals(getString(R.string.rb_simulation_target))) {
                                        /**
                                         * /模拟靶逻辑
                                         */
                                        changeImgStatus();
//                                        imageTarget.setVisibility(View.GONE);
//                                        mVideoTarget.setVisibility(View.GONE);
//                                        imageVideo.setVisibility(View.GONE);
//                                        mScoreTarget.setVisibility(View.VISIBLE);
//                                        mScoreTarget.setImageBitmap(ImageUtil.stringToBitmap(data.getImg_path2()));
//                                        mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(data.getImg_path()));

//                                        mScoreTarget.setTranslate(mWidth * 0.5, mHeight * 0.5965483555845002);
//                                        mScoreTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
                                    } else if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
                                        /**
                                         * 实图靶
                                         */
                                        changeImgStatus();
//                                        imageTarget.setVisibility(View.GONE);
//                                        mScoreTarget.setVisibility(View.GONE);
//                                        imageVideo.setVisibility(View.GONE);
//                                        mVideoTarget.setVisibility(View.VISIBLE);
//                                        mScoreTarget.setImageBitmap(ImageUtil.stringToBitmap(data.getImg_path2()));
//                                        mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(data.getImg_path()));
                                        //坐标系中心点  实图靶修改
//                                        setTargetCore(results);
//                                        GlideUtils.getInstance().loadImage(MainActivity.this, UrlHelper.IMAGE + imageAddress, imageVideo);
//                                        mVideoTarget.showAllTargets(mPoints, mWidth, mHeight, 1);
                                    }

                                    mListScores.setFocusable(true);
                                    mListScores.setFocusableInTouchMode(true);

                                    mListScores.requestLayout();

                                    mAdapter.setNewData(mShootDataVos);
                                    mListScores.scrollToPosition(mAdapter.getItemCount() - 1);

                                    //LogUtil.info("填充数据的时间---------"+(System.currentTimeMillis()-galod_runtime));
                                    if (mRecordingBullet) {

                                        /*float score = (float) 0.0;
                                        if (mShootDataVos != null && mShootDataVos.size() != 0) {
                                            score = mShootDataVos.get(mShootDataVos.size() - 1).getScore();
                                            BigDecimal bigDecimalScore = new BigDecimal(score);
                                            if (0.0 == bigDecimalScore.doubleValue()) {
                                                mSystemTTS.playText(getString(R.string.tts_miss_the_target), "default");
                                            } else if (10.0 == bigDecimalScore.doubleValue()) {
                                                if (bullet_num_today) {
                                                    mSystemTTS.playText(score + getString(R.string.tts_ring), "default");
                                                } else {
                                                    mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring), "default");
                                                }

                                            } else if (-1.0 == bigDecimalScore.doubleValue()) {

                                            } else {
                                                if (bullet_num_today) {
                                                    mSystemTTS.playText(score + getString(R.string.tts_ring) + mShootDataVos.get(mShootDataVos.size() - 1).getOrientation(), "default");
                                                } else {
                                                    //mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring) + mShootDataVos.get(mShootDataVos.size() - 1).getOrientation(), "default");
                                                    mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring), "default");

                                                }
                                            }
                                        }*/
                                    } else if (!mRecordingBullet && mShootDataVos != null && mShootDataVos.size() != 0
                                            && mShootDataVos.get(mShootDataVos.size() - 1).getAngel() != 0 && mBulletLength != mShootDataVos.size()) {
                                        /*float score = (float) 0.0;
                                        if (mShootDataVos != null && mShootDataVos.size() != 0) {
                                            score = mShootDataVos.get(mShootDataVos.size() - 1).getScore();
                                        }
                                        if (score != 0.0) {
                                            BigDecimal bigDecimalScore = new BigDecimal(score);
                                            if (0.0 == bigDecimalScore.doubleValue()) {
                                                mSystemTTS.playText(getString(R.string.tts_miss_the_target), "default");
                                            } else if (10.0 == bigDecimalScore.doubleValue()) {
                                                if (bullet_num_today) {
                                                    mSystemTTS.playText(score + getString(R.string.tts_ring), "default");
                                                } else {
                                                    mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring), "default");
                                                }

                                            } else if (-1.0 == bigDecimalScore.doubleValue()) {


                                            } else {
                                                if (bullet_num_today) {
                                                    //mSystemTTS.playText(score + getString(R.string.tts_ring) + mShootDataVos.get(mShootDataVos.size() - 1).getOrientation(), "default");
                                                    mSystemTTS.playText(score + getString(R.string.tts_ring), "default");

                                                } else {
                                                    //mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring) + mShootDataVos.get(mShootDataVos.size() - 1).getOrientation(), "default");
                                                    mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring), "default");

                                                }
                                            }
                                        } else if (score == 0.0 && mShootDataVos.get(mShootDataVos.size() - 1).getAngel() != 0) {
                                            mSystemTTS.playText(getString(R.string.tts_miss_the_target), "default");
                                        }*/
                                    }
                                    mBulletLength = mShootDataVos.size();

                                    // mAdapter.setNewData(mShootDataVos);
                                    //滚到最后一行
//                                    Toast.makeText(MainActivity.this, "-----", Toast.LENGTH_SHORT).show()
                                } else {
                                    LogUtil.error("-----" + "请求成功--数据为空");
                                }
                                break;
                            //摄像头断开连接
//                            case 3000:
                            //靶位没有添加摄像头
                            case 1001:
                                switchUnknwn();
                                break;
                            default:
                                mSystemTTS.playText(response.body().msg, "default");
                                break;
                        }
                    }

                    @Override
                    public void onError(Response<WhResponse<ShootFireDataTestVo>> response) {
                        super.onError(response);
                        if (tesxs && !mRecordingBullet) {
                            if (mEdDeviceNum.isEnabled()) {
                                mSystemTTS.playText(getString(R.string.tts_clear_set_target), "default");
                            } else {
                                initFireTest(0);
                            }
                        } else if (!tesxs && !mRecordingBullet) {
                            return;
                        }
                        LogUtil.error("-----" + "请求失败" + response.getException().toString());
                    }
                });
    }

    private List<ShootFireVo> getSimulation(List<ResultsBean> results) {
        List<ShootFireVo> all_points1 = new ArrayList<>();
        List<ResultsBean.AllPointsBean> all_points = new ArrayList<>();
        //第一張不為null的靶紙信息
        for (ResultsBean result : results) {
            if (results != null && results.size() != 0 && results.get(0).getAll_points() != null) {
                all_points = result.getAll_points();
            }

            if (paper == null) {
                if (all_points != null && all_points.size() != 0) {
                    if (all_points.get(all_points.size() - 1).getCentre_width() != null &&
                            all_points.get(all_points.size() - 1).getCentre_height() != null) {
                        paper = results.get(0).getAll_points().get(results.get(0).getAll_points().size() - 1);
                        break;
                    }
                }
            }
        }
        if (all_points != null && all_points.size() != 0) {
            //最后一张图
            ResultsBean.AllPointsBean allPointsBean = all_points.get(all_points.size() - 1);

            double tenRadiuProportion = 0.197;
            double tenWidthRadiuProportion = 0.197;
            double tenHeightRadiuProportion = 0.197;
            ShootRegisterVo.RecordsBean from = ShootFireVo.from(allPointsBean.getCut_width(), allPointsBean.getCut_height(),
                    all_points, mWidth, mHeight, paper, tenWidthRadiuProportion, tenHeightRadiuProportion, allPointsBean.getTarget_type());
            all_points1.addAll(from.getAll_points());
        }
        return all_points1;
    }

    private double tenWidthRadiuProportion = 0.0;
    private double tenHeightRadiuProportion = 0.0;

    private List<ShootFireVo> getRealGraph(List<ResultsBean> results) {
        List<ShootFireVo> all_points1 = new ArrayList<>();
        //第一張不為null的靶紙信息
        if (paper == null) {
            if (results != null && results.size() != 0 && results.get(0).getAll_points() != null && results.get(0).getAll_points().size() != 0) {
                if (results.get(0).getAll_points().get(results.get(0).getAll_points().size() - 1).getCentre_width() != null &&
                        results.get(0).getAll_points().get(results.get(0).getAll_points().size() - 1).getCentre_height() != null) {
                    paper = results.get(0).getAll_points().get(results.get(0).getAll_points().size() - 1);
                }
            }
        }

        for (ResultsBean result : results) {
            List<ResultsBean.AllPointsBean> all_points = result.getAll_points();
            if (all_points != null && all_points.size() != 0) {
                //最后一张图
                ResultsBean.AllPointsBean allPointsBean = all_points.get(all_points.size() - 1);
                LogUtil.error("mHeight" + mHeight + "--mWidth" + mWidth);
                LogUtil.error("getCut_height" + allPointsBean.getCut_height() + "--getCut_width" + allPointsBean.getCut_width());
                if (allPointsBean.getCut_height() != null && allPointsBean.getCut_width() != null) {
                    proportionHeight = Ardith.div(mHeight, allPointsBean.getCut_height());
                    proportionWidth = Ardith.div(mWidth, allPointsBean.getCut_width());
                }
                Integer cut_width = allPointsBean.getCut_width();
                Integer cut_height = allPointsBean.getCut_height();
                Double centre_height = allPointsBean.getCentre_height();
                Double centre_width = allPointsBean.getCentre_width();

                if (centre_width != null && cut_width != null && centre_height != null && cut_height != null) {
                    tenWidthRadiuProportion = Ardith.div(centre_width, cut_width);
                    tenHeightRadiuProportion = Ardith.div(centre_height, cut_height);
                }
                ShootRegisterVo.RecordsBean from = ShootFireVo.from(allPointsBean.getCut_width(),
                        allPointsBean.getCut_height(), all_points, mWidth, mHeight, paper, tenWidthRadiuProportion, tenHeightRadiuProportion, allPointsBean.getTarget_type());
                all_points1.addAll(from.getAll_points());
            }
        }
        return all_points1;
    }

    /**
     * 坐标系中心点  实图靶修改
     *
     * @param results
     */
    private void setTargetCore(List<ResultsBean> results) {
        if (results != null && results.size() != 0 && results.get(results.size() - 1).getAll_points() != null && results
                .get(results.size() - 1).getAll_points().size() != 0) {
            double centreX;
            double centreY;
            //修改自定义view坐标系
            LogUtil.error("proportionHeight" + proportionHeight + "--proportionWidth" + proportionWidth);

            if (results.get(results.size() - 1).getAll_points().get(
                    results.get(results.size() - 1).getAll_points().size() - 1).getCentreX() != null &&
                    results.get(results.size() - 1).getAll_points().get(
                            results.get(results.size() - 1).getAll_points().size() - 1).getCentreY() != null) {
                centreX = (results.get(results.size() - 1).getAll_points().get(
                        results.get(results.size() - 1).getAll_points().size() - 1).getCentreX() * proportionWidth);
                centreY = (results.get(results.size() - 1).getAll_points().get(
                        results.get(results.size() - 1).getAll_points().size() - 1).getCentreY() * proportionHeight);
                LogUtil.error("centreX" + centreX + "--centreY" + centreY);
                //设置新的坐标系
//                mVideoTarget.setTranslate(centreX, centreY);
                LogUtil.error("X" + mScoreTarget.getTranslationX() + "----Y" + mScoreTarget.getTranslationY());
            }

        }
    }

    /**
     * @param all_points1
     */
    private void fillNewData(List<ShootFireVo> all_points1) {
        for (ShootFireVo shootFireVo : all_points1) {
            //记弹全部 填充
            if (mRecordingBullet) {
                mAllSrore += shootFireVo.getScore();
                //设置虚拟靶位坐标
                mPoints.add(new Point(shootFireVo.getX(), shootFireVo.getY()));
                //绑定新数据
                mShootDataVos.add(new ShootFireVo(shootFireVo.getScore(), shootFireVo.getOrientation(), shootFireVo.getAngel(),
                        shootFireVo.getX(), shootFireVo.getY(), shootFireVo.getImage(), shootFireVo.isEnable_circle_float(), mAllSrore, shootFireVo.getTarget_type()));
                //精确报靶和模糊报靶切换
                EnableCircleFloat = shootFireVo.isEnable_circle_float();
            }
            //不记弹只填充不脱靶的  || shootFireVo.getAngel() != 0 (方位  在靶纸白边时有数值)
            else if (shootFireVo.getScore() != 0.0 || shootFireVo.getAngel() != 0) {
                mAllSrore += shootFireVo.getScore();
                //设置虚拟靶位坐标
                mPoints.add(new Point(shootFireVo.getX(), shootFireVo.getY()));
                //绑定新数据
                mShootDataVos.add(new ShootFireVo(shootFireVo.getScore(), shootFireVo.getOrientation(), shootFireVo.getAngel(),
                        shootFireVo.getX(), shootFireVo.getY(), shootFireVo.getImage(), shootFireVo.isEnable_circle_float(), mAllSrore, shootFireVo.getTarget_type()));
                //精确报靶和模糊报靶切换
                EnableCircleFloat = shootFireVo.isEnable_circle_float();
            }
        }
    }

    /**
     * 换靶纸
     */
    private void initChangePaPer() {
        OkGo.<WhResponse<ShootPaperVo>>post(UrlHelper.BASE + UrlHelper.SETTING_TARGET_POSITION_RESET_PAPER)
                .params("number", mShootingNum)
                .execute(new DialogCallback<WhResponse<ShootPaperVo>>(this) {
                    @Override
                    public void onSuccess(Response<WhResponse<ShootPaperVo>> response) {
                        LogUtil.error("====" + response.code());
                        switch (response.body().code) {
                            case 0:
                                ToastUtils.show(R.string.tos_paper_replaced_successfully);

                                //替换靶纸id
                                ShootPaperVo data = response.body().data;
                                if (!"0".equals(data.getPaper_id() + "")) {
                                    SPUtils.getInstance().put("PagerId", data.getPaper_id());
                                }
                                //清除数据
                                results.clear();
                                mShootDataVos.clear();
                                mAdapter.setNewData(mShootDataVos);
                                //清除声音和震动防止误触
                                soundList.clear();
                                bleList.clear();
                                //清除坐标点
                                mPoints.clear();
                                //清除保存的靶纸信息
                                paper = null;
//                                mScoreTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
//                                mVideoTarget.showAllTargets(mPoints, mWidth, mHeight, 0);

                                break;
                            default:
                                //相机连接不到;
                                mSystemTTS.playText(response.body().msg, "default");
                                break;
                        }
                    }

                    @Override
                    public void onError
                            (Response<WhResponse<ShootPaperVo>> response) {
                        super.onError(response);
                        LogUtil.error("-----" + "请求失败" + response.getException().toString());
                    }
                });
    }

    /**
     * 换人接口-目前没用
     */
    private void initubstitutions() {
        OkGo.<WhResponse<ShootPeopleVo>>post(UrlHelper.BASE + UrlHelper.SETTING_TARGET_POSITION_RESET_PEOPLE)
                .params("number", mShootingNum)
                .params("paper_id", initSpPagerId())
                .execute(new DialogCallback<WhResponse<ShootPeopleVo>>(this) {
                    @Override
                    public void onSuccess(Response<WhResponse<ShootPeopleVo>> response) {
                        LogUtil.error("====" + response.code());
                        switch (response.body().code) {
                            case 0:
                                ToastUtils.show(R.string.tos_end_of_substitution);

                                //替换靶纸id
                                ShootPeopleVo data = response.body().data;
                                if (!"0".equals(data.getPeople_id() + "")) {
                                    SPUtils.getInstance().put("PeopleId", data.getPeople_id());
                                }

                                break;
                            default:
                                //相机连接不到;
                                mSystemTTS.playText(response.body().msg, "default");
                                break;
                        }
                    }

                    @Override
                    public void onError
                            (Response<WhResponse<ShootPeopleVo>> response) {
                        super.onError(response);
                        LogUtil.error("-----" + "请求失败" + response.getException().toString());
                    }
                });
    }

    /**
     * 气象定时任务
     *
     * @param timer 计时器
     */
    private void initMeteorologicalMonitor(Timer timer) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (!mEdDeviceNum.isEnabled()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //"http://192.168.1.128:8088/"
                            OkGo.<WhResponse<MeteorologicalVo>>get(UrlHelper.IMAGE + UrlHelper.SETTINF_TARGET_GET_METEOROLOGICAL_INFO)
                                    .execute(new JsonCallback<WhResponse<MeteorologicalVo>>() {
                                        @Override
                                        public void onSuccess(Response<WhResponse<MeteorologicalVo>> response) {
                                            //获取气象信息
                                            MeteorologicalVo meteorologicalVo = response.body().data;
                                            Log.e("TAG", meteorologicalVo.toString());

                                            // Update UI elements here
                                            PressureTx.setText("气压:" + meteorologicalVo.getPressure() + "kPa");
                                            TemperatureTx.setText("温度:" + meteorologicalVo.getTemperature() + "℃");
                                            HumidityTx.setText("湿度:" + meteorologicalVo.getHumidity() + "%HR");
                                            RainfallTx.setText("降雨量:" + meteorologicalVo.getRainfall() + "mm");
                                            WinddirectionTx.setText("风向:" + meteorologicalVo.getWind_direction());
                                            WindspeedTx.setText("风速:" + meteorologicalVo.getWind_speed() + "m/s");
                                            IlluminanceTx.setText("光照:" + meteorologicalVo.getIlluminance() + "Lux");
                                        }

                                        @Override
                                        public void onError(Response<WhResponse<MeteorologicalVo>> response) {
                                            super.onError(response);
                                            Toast.makeText(MainActivity.this, "气象信息获取失败...", Toast.LENGTH_SHORT).show();
                                            mSystemTTS.playText("气象信息获取失败，请检查", "default");
                                        }
                                    });
                        }
                    });
                }
            }
        };//
        timer.schedule(task, 2000, 10 * 1000 * 60 * 10);
    }


    /**
     * 开枪接口-目前没用
     */
    private void initFire() {
        OkGo.<WhResponse<ShootFireDataVo>>post(UrlHelper.BASE + UrlHelper.SETTING_TARGET_POSITION_FIRE)
                .params("number", mShootingNum)
                .params("paper_id", initSpPagerId())
                .params("people_id", initSpPeopleId())
                .params("race_id", initSpRace_Id())
                .params("group_id", initSpGroup_Id())
                .execute(new JsonCallback<WhResponse<ShootFireDataVo>>() {
                    @Override
                    public void onSuccess(Response<WhResponse<ShootFireDataVo>> response) {
                        switch (response.body().code) {
                            case 0:
                                ShootFireDataVo data = response.body().data;
                                if (data.getAll_points() != null && data.getAll_points().size() != 0) {
                                    imageAddress = data.getAll_points().get(data.getAll_points().size() - 1).getImage();
                                    // mDataBeans.clear();
                                    //  mDataBeans = ShootDataUtil.getShootCompleteData(response.body().data);
                                    //  LogUtil.error("-----" + response.body() + "---" + response.message() + "---" + response.code());
                                    //   LogUtil.error("-----" + response.body().data);
                                    //输入新数据
                                    //   mAdapter.setNewData(mDataBeans);
                                    //设置射击点bn
                                    //设置
                                    mPoints.clear();
                                    mShootDataVos.clear();
                                    mAllSrore = 0;
//                                    boolean isEnableCircleFloat = SPUtils.getInstance().getBoolean("isEnableCircleFloat");
                                    for (ShootFireVo all_point : data.getAll_points()) {
                                        mAllSrore += all_point.getScore();
                                        mPoints.add(new Point(all_point.getX(), all_point.getY()));
                                        mShootDataVos.add(new ShootFireVo(all_point.getScore(), all_point.getOrientation(), all_point.getAngel(),
                                                all_point.getX(), all_point.getY(), all_point.getImage(), EnableCircleFloat, mAllSrore, all_point.getTarget_type()));
                                    }
//                                    Toast.makeText(MainActivity.this, "=====", Toast.LENGTH_SHORT).show();

                                    mListScores.setFocusable(true);
                                    mListScores.setFocusableInTouchMode(true);

                                    mListScores.requestLayout();
                                    mAdapter.setNewData(mShootDataVos);
                                    mListScores.scrollToPosition(mAdapter.getItemCount() - 1);

                                    // mAdapter.setNewData(mShootDataVos);
                                    //滚到最后一行
//                                    Toast.makeText(MainActivity.this, "-----", Toast.LENGTH_SHORT).show();
                                    //靶子状态切换
//                                    if (mScoreTarget.getVisibility() == View.VISIBLE) {
//                                        mScoreTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
//                                    } else if (imageVideo.getVisibility() == View.VISIBLE) {
//                                        GlideUtils.getInstance().loadImage(MainActivity.this, UrlHelper.IMAGE + imageAddress, imageVideo);
//                                    }


                                    //
                                    float score = (float) 0.0;
                                    if (mShootDataVos != null && mShootDataVos.size() != 0) {
                                        score = mShootDataVos.get(mShootDataVos.size() - 1).getScore();
                                    }
                                    BigDecimal bigDecimalScore = new BigDecimal(score);
                                    if (0.0 == bigDecimalScore.doubleValue()) {
                                        mSystemTTS.playText(getString(R.string.tts_miss_the_target), "default");
                                    } else if (10.0 == bigDecimalScore.doubleValue()) {
                                        if (bullet_num_today) {
                                            mSystemTTS.playText(score + getString(R.string.tts_ring), "default");
                                        } else {
                                            mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring), "default");
                                        }

                                    } else {
                                        if (bullet_num_today) {
                                            mSystemTTS.playText(score + getString(R.string.tts_ring) + mShootDataVos.get(mShootDataVos.size() - 1).getOrientation(), "default");
                                        } else {
                                            mSystemTTS.playText(StrUtil.Format(score) + getString(R.string.tts_ring) + mShootDataVos.get(mShootDataVos.size() - 1).getOrientation(), "default");
                                        }
                                    }
                                } else {
                                    LogUtil.error("-----" + "请求成功--数据为空");
                                }
                                break;
                            //摄像头断开连接
                            case 3000:

                                //靶位没有添加摄像头
                            case 1001:
                                switchUnknwn();
                                break;
                            default:
                                mSystemTTS.playText(response.body().msg, "default");
                                break;
                        }

                    }

                    @Override
                    public void onError(Response<WhResponse<ShootFireDataVo>> response) {
                        super.onError(response);
                        LogUtil.error("-----" + "请求失败" + response.getException().toString());
                    }
                });

    }

    /**
     * 开始结束接口
     */
    private void initStartEnd(int type) {
        OkGo.<WhResponse<ShootPaperVo>>post(UrlHelper.BASE + UrlHelper.SETTING_TARGET_POSITION_START_END)
                .params("number", mShootingNum)
                .params("status", type)
                .execute(new DialogCallback<WhResponse<ShootPaperVo>>(MainActivity.this) {
                    @Override
                    public void onSuccess(Response<WhResponse<ShootPaperVo>> response) {
                        LogUtil.error("====" + response.code());
                        switch (response.body().code) {
                            case 0:
                                //开始射击  开始时清空数据（换人操作）
                                if (type == 1) {
                                    ToastUtils.show(R.string.tos_start_projectile);
                                    StartEndBoolean = true;
                                    //俱乐部模式下开启清空数据
//                                    mShootDataVos.clear();
//                                    mAdapter.setNewData(mShootDataVos);
//                                    //清除坐标点
//                                    mPoints.clear();
//                                    mScoreTarget.showAllTargets(mPoints, mWidth, mHeight);
                                    //清除数据
                                    if (results != null) {
                                        results.clear();
                                    }
                                    mShootDataVos.clear();
                                    mAdapter.setNewData(mShootDataVos);
                                    //清除坐标点
                                    mPoints.clear();
//                                    mScoreTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
//                                    mVideoTarget.showAllTargets(mPoints, mWidth, mHeight, 0);
                                } else {
                                    StartEndBoolean = false;
                                    ToastUtils.show(R.string.tos_closing_the_bomb);

                                }
                                break;
                            default:
                                //相机连接不到;
                                mSystemTTS.playText(response.body().msg, "default");
                                break;
                        }
                    }

                    @Override
                    public void onError
                            (Response<WhResponse<ShootPaperVo>> response) {
                        super.onError(response);
                        LogUtil.error("-----" + "请求失败" + response.getException().toString());
                    }
                });
    }

    /**
     * 收到Socket传来的Code之后，上传震动至后端的接口
     */
    private void initUpdatasensorlist() {
        Gson gson = new Gson();
        String s = gson.toJson(mBluetoothDataVos);
        OkGo.<WhResponse<ShootPaperVo>>post(UrlHelper.IMAGE + UrlHelper.SETTINF_TARGET_POST_ZD_UPDATASENSORLIST)
                .params("number", Integer.valueOf(mShootingNum))
                .params("pressureList", s)
                .execute(new DialogCallback<WhResponse<ShootPaperVo>>(MainActivity.this) {
                    @Override
                    public void onSuccess(Response<WhResponse<ShootPaperVo>> response) {
                        switch (response.body().code) {

                        }
                    }
                });
    }

    /**
     * 双击两次退出应用
     */
    @Override
    public void onBackPressed() {
        //按两次退出
        if (System.currentTimeMillis() - mTime < 1500) {
            super.onBackPressed();
        } else {
            ToastUtils.show(R.string.tos_double_click_exit);
            mTime = System.currentTimeMillis();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (client != null) {
            client.unregisterMessageReceive();
            client.disConnect();
        }

        //关闭蓝牙
        try {
            // 解注册广播过滤器
            unregisterReceiver(UARTStatusChangeReceiver);
            unregisterReceiver(statusChangeReceiverUART);
        } catch (Exception ignore) {
            LogUtil.error(ignore.toString());
        }
        // 解绑定服务
        unbindService(mServiceConnection);
        unbindService(mServiceConnectionUART);
        // 关闭服务对象
        mService.stopSelf();
        mServiceUART.stopSelf();
        mService = null;
        mServiceUART = null;

        //注销socket
        //stopService(new Intent(this, SocketService.class));
        //关闭tts语音
        // mSystemTTS.stopSpeak();
        //关闭轨道服务
        stopService(new Intent(MainActivity.this, CameraService.class));
        LogUtil.error("-----------------");
        SPUtils.getInstance().put("blueAddress", "");
        SPUtils.getInstance().put("blueName", "");

        SPUtils.getInstance().put("blueAddressUART", "");
        SPUtils.getInstance().put("blueNameUART", "");

        System.exit(0);
    }

    /**
     * 申请位置和存储权限
     */
    private void checkPermissions() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        XXPermissions.with(this)
                // 可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                //.constantRequest()
                // 支持请求6.0悬浮窗权限8.0请求安装权限
                //.permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES)
                // 不指定权限则自动获取清单中的危险权限
                .permission(Permission.Group.LOCATION, Permission.Group.STORAGE)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean all) {

                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });
    }


    /**
     * 菜单点击事件
     *
     * @param index 菜单从下往上123
     */
    @Override
    public void onClick(int index) {
        switch (index) {
            case 1:
                //开始记弹
                if (!StartEndBoolean) {
                    initStartEnd(1);
                } else {
                    ToastUtils.show(getString(R.string.main_start));
                    mSystemTTS.playText(getString(R.string.main_start), "default");
                }
                break;
            case 2:
                //结束记弹
                initStartEnd(0);
                break;
            case 3:
                //换靶纸
                if (mEdDeviceNum.isEnabled()) {
                    mSystemTTS.playText(getString(R.string.tts_clear_set_target), "default");
                } else {
                    initChangePaPer();
                }
                break;
            case 4:
                //开枪校准
                //  initFire();
                //开枪辅助
                if (NoFastClickUtils.isFastClick(mDefaultFireTime)) {
                    LogUtil.info("第二次");
                    return;
                }
                LogUtil.info("第一次");
                if (mEdDeviceNum.isEnabled()) {
                    mSystemTTS.playText(getString(R.string.tts_clear_set_target), "default");
                } else {
                    ToastUtils.show(getString(R.string.tos_Identifying_bullet_holes));
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            initFireTest(0);
//                            initFire();
                        }
                    }, 1500);
                }
                break;

        }
    }

    /**
     * 菜单打开事件
     *
     * @param isClose
     */
    @Override
    public void onOpen(boolean isClose) {

    }

    /**
     * 处理视频靶图片
     *
     * @param imgMsg
     */
    private void handleVideoImg(String imgMsg) {
        //判断不能为空
        if (NotNullHelper.notEmpty(imgMsg)) {
            wsImgAddress = imgMsg;
            //如果长度很高的话，判断为BASE-64的
            if (imgMsg.length() > 1000) {
                mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(imgMsg));
            } else {
                wsImgAddress = wsImgAddress.replace("C:\\shoot-data\\", UrlHelper.IMAGE);
                //否则的话判断为HTTP样式的
                Glide.with(MainActivity.this)
                        .load(wsImgAddress)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        //注:是否跳过内存缓存，设置为false，如为true的话每次闪烁也正常~
                        .skipMemoryCache(false)
                        .placeholder(mVideoTarget.getDrawable())
                        //取消Glide自带的动画
                        .dontAnimate()
                        .into(mVideoTarget);
            }
        }
    }

    Client client = null;

    /**
     * 启动WebSocket
     */
    private void startWebSocketClient() {
        //启动WebSocket
//        WsClient instance = WsClient.getInstance(this);
//        instance.init(UrlHelper.WS_BASE);
//        instance.init("ws://192.168.1.50:8080");
        client = new Client(eventLis);
        client.registerMessageReceive(new OnWsMessageReceiveListener() {
            @Override
            public void onMessageReceive(String appMessage) {
                //通过EventBus发送数据
                AppEventBus.getInstance().post(EventBusCode.EVENT_TYPE, appMessage);
            }
        });
        client.startConnect();
    }

    private EventListener eventLis = new EventListener() {
        final String TAG = "NETTY-WEB-SOCKET-STATUS";
        final String TAG_HEADER = "WebSocket-Status:";

        /**
         * 连接开始
         *
         * @param inetSocketAddress
         */
        @Override
        public void connectStart(InetSocketAddress inetSocketAddress) {
            super.connectStart(inetSocketAddress);
            LoggerHelper.e(TAG, TAG_HEADER + "connectStart");
        }

        /**
         * 连接成功
         */
        @Override
        public void connectSuccess() {
            super.connectSuccess();
            LoggerHelper.e(TAG, TAG_HEADER + "connectSuccess");
        }

        /**
         * 连接出现异常
         *
         * @param throwable
         */
        @Override
        public void connectionException(Throwable throwable) {
            super.connectionException(throwable);
            LoggerHelper.e(TAG, TAG_HEADER + "connectionException");
        }

        /**
         * 连接失败
         *
         * @param inetSocketAddress
         * @param ioe
         */
        @Override
        public void connectFailed(InetSocketAddress inetSocketAddress, IOException ioe) {
            super.connectFailed(inetSocketAddress, ioe);
            LoggerHelper.e(TAG, TAG_HEADER + "connectFailed");
        }

        /**
         * 连接断开
         */
        @Override
        public void connectionBroken() {
            super.connectionBroken();
            LoggerHelper.e(TAG, TAG_HEADER + "connectionBroken");
        }

        /**
         * 连接释放
         *
         * @param connection
         */
        @Override
        public void connectionReleased(Connection connection) {
            super.connectionReleased(connection);
            LoggerHelper.e(TAG, TAG_HEADER + "connectionReleased");
            client.startConnect();
        }

        /**
         * 发送开始
         *
         * @param call
         */
        @Override
        public void sendMsgStart(Call call) {
            super.sendMsgStart(call);
            LoggerHelper.e(TAG, TAG_HEADER + "sendMsgStart");
        }

        /**
         * 发送结束
         *
         * @param call
         */
        @Override
        public void sendMsgEnd(Call call) {
            super.sendMsgEnd(call);
            LoggerHelper.e(TAG, TAG_HEADER + "sendMsgEnd");
        }

        /**
         * 发送失败
         *
         * @param call
         */
        @Override
        public void sendMsgFailed(Call call) {
            super.sendMsgFailed(call);
            LoggerHelper.e(TAG, TAG_HEADER + "sendMsgFailed");
        }

        @Override
        public void sendHeartStart(Call call) {
            super.sendHeartStart(call);
            LoggerHelper.e(TAG, TAG_HEADER + "sendHeartStart");
        }
    };

    /**
     * 接收WebSocket改变的状态
     *
     * @param status {@link WsStatus}
     */
    @Override
    public void receiveStatus(WsStatus status) {
        final String tag = "receiveStatus";
        newRx.add(Observable.just(status)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((data -> {
                    /*switch (data) {
                        default:
                        case ON_OPEN:
                            LoggerHelper.e(tag, "receiveStatus---ON_OPEN");
                            break;
                        case ON_MESSAGE:
                            LoggerHelper.e(tag, "receiveStatus---ON_MESSAGE");
                            break;
                        case ON_CLOSING:
                            LoggerHelper.e(tag, "receiveStatus---ON_CLOSING");
                            break;
                        case ON_CLOSED:
                            LoggerHelper.e(tag, "receiveStatus---ON_CLOSED");
                            break;
                        case ON_FAILURE:
                            LoggerHelper.e(tag, "receiveStatus---ON_FAILURE");
                            break;
                        case ON_RECONNECT:
                            LoggerHelper.e(tag, "receiveStatus---ON_RECONNECT");
                            break;
                    }*/
                }), (e -> {
                    LoggerHelper.e(tag, e.getMessage() + "");
                }))
        );

    }

    /**
     * 测试Websocket接收数据
     *
     * @param msg webSocket的数据
     */
    @Deprecated
    private static void debugReceiveMsg(String msg) {
        try {
            TypeToken<WhResponse<ShootFireDataTestVo>> typeToken = new TypeToken<WhResponse<ShootFireDataTestVo>>() {
            };
            WhResponse whResponse = new Gson().fromJson(msg, typeToken.getType());
            switch (whResponse.code) {
                case 100001:
                    LoggerHelper.e("receiveMsg---");
                    break;
            }
        } catch (Exception e) {
            LoggerHelper.e(e.getMessage());
        }
    }

    //本地模拟靶的圆心坐标点以及十环半径长度

    private final int LOCAL_CENTER_X = 517, LOCAL_CENTER_Y = 606, LOCAL_CENTER_RADIUS = 104;

    /**
     * 将实际胸环靶图上的坐标点转换为模拟静态胸环靶图上的坐标点并标注
     *
     * @param absoluteRadius 视频靶的十环半径
     * @param relativeX      视频靶中标点的X坐标
     * @param relativeY      视频靶中标点的Y坐标
     * @return 返回一个Point，用来在控件上绘制点位
     */
    private PointF getOffset(int absoluteRadius, int relativeX, int relativeY) {
        // 计算比例因子
        float scale = absoluteRadius / LOCAL_CENTER_RADIUS;
        // 计算实际胸环靶图中心点在模拟静态胸环靶图上的坐标
//        float canvasX = LOCAL_CENTER_X + scale * relativeX;
//        float canvasY = LOCAL_CENTER_X + scale * relativeX;
        float canvasX = scale * relativeX;
        float canvasY = scale * relativeX;
        //返回实际的坐标点
        return new PointF(canvasX, canvasY);
    }

    //boolean isReceiveWsMsg = false;
    String wsImgAddress = "";

    /**
     * webSocket接收到文字消息
     *
     * @param msg
     */
    @Override
    public void receiveMsg(String msg) {
        final String tag = "receiveMsg";
//        ServerMsg serverMsg = new Gson().fromJson(msg, ServerMsg.class);
//        PointF offset = getOffset(Integer.valueOf(serverMsg.getRadius()), Integer.valueOf(serverMsg.getRelativeX()), Integer.valueOf(serverMsg.getRelativeY()));
//        BaseApplication.room.receiveBeanDao().insertOne(new ReceiveMsgBean(serverMsg.getNumber(), serverMsg.getVideoTarget(), serverMsg.getX(), serverMsg.getY(), serverMsg.getAngle(), Float.valueOf(serverMsg.getScore()), serverMsg.getRelativeX(), serverMsg.getRelativeY(), serverMsg.getRadius(), offset.x, offset.y, com.blankj.utilcode.util.TimeUtils.getNowMills()));


        /*newRx.add(Observable.create(emitter -> {
//                    isReceiveWsMsg = true;
//                    wsImgAddress = serverMsg.getVideoTarget();
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((t -> {
                }), (e -> {

                })));*/

    }

    DetailViewModel viewModel;

    /**
     * 创建Viewmodel，用来监听数据
     */
    private void createViewModel() {
        viewModel = new ViewModelProvider(MainActivity.this).get(DetailViewModel.class);
        viewModel.allData.observe(MainActivity.this, (datas -> {
            if (NotNullHelper.notEmpty(datas)) {//&& isOpenRecordBullet

            }
        }));

    }

    private void changeImgStatus() {
//        isOpenRecordBullet
        //不同靶不同数据填充
        if (rbtnSim.getText().toString().equals(getString(R.string.rb_simulation_target))) {
            /**
             * /模拟靶逻辑
             */
            imageTarget.setVisibility(View.GONE);
            mVideoTarget.setVisibility(View.GONE);//视频靶
            imageVideo.setVisibility(View.GONE);
            mScoreTarget.setVisibility(View.VISIBLE);//实图靶
//            mScoreTarget.setImageBitmap(ImageUtil.stringToBitmap(data.getImg_path2()));
//            mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(data.getImg_path()));
            if (NotNullHelper.notEmpty(wsImgAddress)) {
                handleVideoImg(wsImgAddress);
            }
        } else if (rbtnSim.getText().toString().equals(getString(R.string.rb_video_target))) {
            /**
             * 实图靶
             */
            imageTarget.setVisibility(View.GONE);
            mScoreTarget.setVisibility(View.GONE);
            imageVideo.setVisibility(View.GONE);
            mVideoTarget.setVisibility(View.VISIBLE);
            if (NotNullHelper.notEmpty(wsImgAddress)) {
                handleVideoImg(wsImgAddress);
            }
//            mScoreTarget.setImageBitmap(ImageUtil.stringToBitmap(data.getImg_path2()));
//            mVideoTarget.setImageBitmap(ImageUtil.stringToBitmap(data.getImg_path()));
        }
    }

    private static final int STATIC_TARGET_RADIUS = 104;

    /**
     * 绘制弹孔
     */
    private Bitmap loadPointTargetImage(List<ShootFireVo> listData) {
        Bitmap bitmap =
                BitmapFactory.decodeResource(getResources(), R.drawable.bg_canvas)
                        .copy(Bitmap.Config.ARGB_8888, true);
        Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap, 1039, 1069, true);
        bitmap.recycle();
        for (int i = 0; i < listData.size(); i++) {
            ShootFireVo point = listData.get(i);
            ImageConverter.convertToStaticTarget(
                    bitmap2,
                    point.getAngel(),
                    point.getX(),
                    point.getY(),
                    i == listData.size() - 1
            );
        }
        return bitmap2;
    }

    public Bitmap convertToStaticTarget(
            Bitmap bitmap,
            int actualRadius,
            int relativeX,
            int relativeY,
            boolean isLastPoint
    ) {
        // 计算比例因子
        double scaleFactor = STATIC_TARGET_RADIUS / actualRadius;
        // 计算实际胸环靶图中心点在模拟静态胸环靶图上的坐标
        int staticCenterX = (int) (scaleFactor * relativeX);
        int staticCenterY = (int) (scaleFactor * relativeY);

        LogUtil.error("main 标注点 x:" + staticCenterX + "   y：" + staticCenterY);
        //标注点
        drawCircle(bitmap, staticCenterX, staticCenterY, isLastPoint);
        return bitmap;
    }

    private Bitmap drawCircle(Bitmap image, int centerX, int centerY, boolean isLastPoint) {
        Canvas canvas = new Canvas(image);
        Paint paint = new Paint();
        // 启用抗锯齿
        paint.setAntiAlias(true);
        if (isLastPoint) { //最后一个点绘制为绿色
            paint.setColor(Color.GREEN);
        } else {
            paint.setColor(Color.RED);
        }
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(8f);
        int circleRadius = 13;
        canvas.drawCircle(centerX, centerY, circleRadius, paint);
        if (isLastPoint) { //最后一个点绘制为绿色
            paint.setColor(Color.RED);
        } else {
            paint.setColor(Color.BLUE);
        }
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(centerX, centerY, (circleRadius - 4), paint);
        return image;
    }
}
